This question already has answers here:
How do I make a JavaScript variable completely immutable?
(3 answers)
Closed last year.
In javascript, if I create a const array, I can still modify the object the variable points to:
// 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.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
const x = [1,2,3];
x.push(4);
console.log(x);
x=55 // But this is illegal and will error
console.log(x);
Is there a way to make the elements in an array immutable as well? Similar to something like const int* const x; in C?
You can use Object.freeze to prevent an object (or array) from being changed:
const x = [1, 2, 3];
Object.freeze(x);
x.push(4); // This will throw an exception
objects frozen with Object.freeze() are made immutable.
Here are the docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
Example:
const x = [1,2,3];
Object.freeze(x);
Related
This question already has answers here:
Why can I change a constant object in javascript
(12 answers)
JavaScript ES6 `const a = {}` is mutable. Why? [duplicate]
(2 answers)
Closed 1 year ago.
I came across this interesting concept where const behave differently for number, string, Boolean vs Object, arrays.
const num1 = 10
num1 = 20 //throws error
const arr1 = [1,2,3,4]
arr1.push(5) //works
arr1.pop() //works
arr1[2] = 7 //works
arr1 = [2,3] //throws error
For array & objects it allows change in value but throws error in assignment. Is it mean, there is no advantage of declaring object or array as const, as you can change all values anytime?
If anyone can explain, I would like to know, how, behind the scene, const works?
The const declaration creates a read-only reference to a value.
The value it holds is still immutable. Both array and object are holding some values. Those values and properties can be changed but same variable identifier cannot be reassigned.
Here arr1 is an variable identifier
const arr1 = [1,2,3,4]
arr1.push(5) //works // changing the value
arr1.pop() //works //changing the value
arr1[2] = 7 //works // changing the value
Here arr1 got reassigned so it is throwing an error
arr1 = [2,3] //throws error // reassigning the same variable
This question already has answers here:
Using reserved words as property names, revisited
(4 answers)
Closed 3 years ago.
I wrote.
let const = 10;
and got error.and for objects everything works
let x = {const:10}
What is the difference.
Variables can be used in the same places as you can use the const keyword. If you could use const as a variable name it would be hard to distinguish between the two.
That is not the case for property names; the syntax will always be clear that it refers to a property name.
const is a reserved keyword you cannot use as variable name, so the first one is invalid syntax,
let const = 10
In second example you're using const as key which can be any string
let x = {const:10}
console.log(x)
This question already has answers here:
What is "undefined x 1" in JavaScript?
(5 answers)
Closed 6 years ago.
We all know the difference between array literals and array constructors is subtle but can be important. There seems to be another difference that is not noted in the referenced link. Take the following:
var x = new Array(5); // [undefined x 5];
var newArr = x.map(function () {return 'newValue'});
console.log(newArr); // [undefined x 5];
vs
var y = [undefined, undefined, undefined, undefined, undefined];
var newArr = y.map(function () {return 'newValue'});
console.log(newArr); // ['newValue', 'newValue', 'newValue', 'newValue', 'newValue'];
I would expect x and y to both be array instances and return the same result from the .map method. Seemingly oddly though, the array x produces an array that is not mappable whilst the literal y is mappable.
Why does x and y return different results from the .map method?
Thanks for any help.
MDN:
map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).
This question already has answers here:
Why can I change a constant object in javascript
(12 answers)
JavaScript const Keyword
(8 answers)
Closed 7 years ago.
Using JavaScript ES6, I am surprised that doing:
const a = {};
a.foo = 'bar';
a.foo = 'car';
Is valid. Why is this? I would have assumed const would mean you cannot change the a empty object and apply new properties. Even further, I would also have assumed you cannot change the value of a property of a once it is set.
Only the variable assignment is constant. Any objects or arrays referenced stay mutable.
const a = {one: 1};
a.three = 3; // this is ok.
a = {two: 2}; // this doesn't work.
What you can do is use Object.freeze:
const a = {one: 1};
Object.freeze(a);
a.three = 3; // silently fails.
// a is still {one: 1} here.
No, const a means you cannot change the value of the variable a. Its value is always the same object; changing properties of an object doesn't make it into a different object.
Using an analogy, I am the same Person whether amadan.jacket = null or amadan.jacket = "Heavy Winter Jacket". amadan is constant.
To make the properties immutable, you would either have to make the properties explicitly readonly by writable: false, or use Object.freeze or Object.seal (differences) to make the entire object immutable.
This question already has answers here:
JavaScript by reference vs. by value [duplicate]
(4 answers)
Closed 7 years ago.
I want to know if javascript does shallow or deep copy when copying objects.
const a = ['value1', 'value2'];
const b = ['value3', 'value4'];
const new_ab = [a, b];
new_ab are going to have new allocated values or a reference? If it is a deep copy, how can I make it to be swallow? Thanks.
As alluded in the comments, JavaScript operates entirely on references, the only exception being that primitive values are kept on the stack and a program does not therefore require a reference to access them. In your example all variable declarations create new values - each an instance of Array - however what is returned from declaring an array is a reference, not the array itself. For example, [1, 2] is an array of values (integers), but [a, b] is an array of references.
So... nothing is copied. We can demonstrate this by placing an object as an element of an array and inspecting that a previously assigned property is still accessible through the new 'parent' array.
(And to answer your question in the comments, yes, your example is more performant than if you (or JavaScript) were to copy values.)
'use strict';
const arrayOne = [];
arrayOne.someProperty = "This string is a property of `arrayOne`, " +
"accessed via the reference to it in `arrayTwo`."
const arrayTwo = [arrayOne];
span.innerHTML = arrayTwo[0].someProperty;
<span id="span"></span>