Skip to content Skip to sidebar Skip to footer

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).

Solution 1:

Just use Object.freeze

const immutableArray = Object.freeze([1,2,4])

Solution 2:

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().

Solution 3:

The way to do it without const is to use Object.defineProperty, and like I wanted, it behaves like var in terms of scope:

{
    Object.defineProperty(typeofglobal === "object" ? global : window, "PI", {
        value:        Object.seal(3.141593),
        enumerable:   true,
        writable:     false,
        configurable: false
    });
}
console.log(PI); // 3.141593

The only problem is that it that it doesn't throw an error outside of strict mode.

Post a Comment for "How Do I Make A Javascript Variable Completely Immutable?"