Related Articles

Related Articles

Difference between Object.freeze() and const in JavaScript
  • Last Updated : 15 Apr, 2020

ES6 has brought several new features and methods into JavaScript since its release. Amongst these new features are Object.freeze() method and const. Sometimes people get confused between Object.freeze() method and const but the Object.freeze() and const are completely different. In this article we will explain the differences between these two.

const: The const keyword creates a read-only reference to a value. Variables created by the const keyword are immutable. In other words, you can’t reassign them to different values. Trying to reassign a constant variable will result in a TypeError.

  • Example 1:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script>
        let myName = "Geeksforgeeks"
        console.log(myName) 
      
        // Uncaught TypeError
        myName = "gfg"                    
    </script>

    chevron_right

    
    

The const keyword ensures that the variable created is read-only. But It doesn’t mean that the actual value to which the const variable reference is immutable. Even though the person variable is constant. However, you can change the value of its property. But you cannot reassign a different value to the person constant.

  • Example 2:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script>
        const person = {
            name: "Geeksforgeeks"
        };
              
    // No TypeError
    person.name = "gfg";
    console.log(person.name); 
    </script>                    

    chevron_right

    
    

Object.freeze() method: If you want the value of the person object to be immutable, you have to freeze it by using the Object.freeze() method.

  • Example 1:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script>
         const person = Object.freeze({name: "Geeksforgeeks"});
         
         // TypeError
         person.name = "gfg"
    </script>

    chevron_right

    
    

The Object.freeze() method is shallow, meaning that it can freeze the properties of the object, not the objects referenced by the properties.

  • Exxample 2:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script>
    const person = Object.freeze({
        name: 'Geeksforgeeks',
        address: {
            city:"Noida"
        }
    });
    </script>

    chevron_right

    
    

  • But the person.address object is not immutable, you can add a new property to the person.address object as follows:
    // No TypeError
    person.address.country = "India";

Conclusion:

  • const prevents reassignment.
  • Object.freeze() prevents mutability.

full-stack-img




My Personal Notes arrow_drop_up
Recommended Articles
Page :