Search code examples
javascriptimmutabilityvar

How do I make a JavaScript variable completely immutable?


I've heard similar questions, but not the answer that I wanted; I do not count const because: 1). it doesn't actually make it immutable, it only makes the reference immutable 2). it messes with the scope, and I want it to work outside the block, too 3). not all browsers support it yet

 {
     const hello = ["hello", "world"];
     hello.push("!!!");
     console.log(hello);//outputs "hello", "world", "!!!"
 }
 //and it doesn't, and shouldn't, work here
     console.log(hello);

Solution

  • You can use Object.freeze for this (obviously only on objects).

    const hello = Object.freeze(["hello", "world"]);
    
    // hello.push("!!!");
    // will throw "TypeError: can't define array index property past the end of an array with non-writable length"
    
    // hello.length = 0;
    // will fail silently
    
    // hello.reverse();
    // will throw "TypeError: 0 is read-only"
    
    // hello[0] = "peter";
    // will fail silently

    From MDN:

    The Object.freeze() method freezes an object. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. In addition, freezing an object also prevents its prototype from being changed. freeze() returns the same object that was passed in.

    However, there is no keyword to define a completely immutable variable without using Object.freeze or Object.seal on the variable's value.

    For a less restrictive approach Javascript also has Object.seal().