Reputation: 1672
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);
Upvotes: 3
Views: 2757
Reputation: 1672
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(typeof global === "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.
Upvotes: 1
Reputation: 56753
You can use Object.freeze
for this (obviously only on object
s).
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 anobject
. 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()
.
Upvotes: 2
Reputation: 21317
Just use Object.freeze
const immutableArray = Object.freeze([1,2,4])
Upvotes: 4