Does the const
keyword in JavaScript create an immutable reference to immutable data structures? [I\'m assuming that immutable data structures exist in JavaScri
Yes, it does create an immutable reference, but it is not been standardized and is not supported in all browsers.
See this MDN article on the const keyword for details and compatability.
However, it doesn't do anything to set the referenced data structure as immutable. Several answers below address that question using, for example, Object.freeze
const is a proposed feature of ECMAScript(together with a properly block-scoped let it is supposed to replace var and implicit global). ECMAScript Harmony is a grab-bag of ideas for the next versions of ECMAScript.
If you looking for read only variable, you can do like this
var constants = new (function() {
var x = 200;
this.getX = function() { return x; };
})();
You can use like this
constants.getX()
You can create CONST like values using ES5 Object.defineProperty. The crummy part is that it must be bound to an object
CONSTS = {};
Object.defineProperty(CONSTS, 'FOO', {
value: 'bar'
});
CONSTS.FOO = 'derp' // Will throw error in strict mode
delete CONSTS.FOO // will throw error in strict mode
For example:
const basket = [1,2,3];
//Even though the variable is declared as const this one works
basket[0] = 1111;
console.log(basket);
//This one throws an error
basket = "Other primitive type."
Yes that is right. A const would only declare a read-only named constant. Changing its value will have no effect.
Reference for const on MDN:
Const creates a constant that can be global or local to the function in which it is declared. Constants follow the same scope rules as variables.
The value of a constant cannot change through re-assignment, and a constant cannot be re-declared. Because of this, although it is possible to declare a constant without initializing it, it would be useless to do so.
A constant cannot share its name with a function or a variable in the same scope.
Here's the browser compatibility matrix.
Wrong. It is not immutable, from the MDN Documentation for const:
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.