I am learning basics of JavaScript again and want to know how actually JavaScript applies in my code. As you can see above, why constants' property or value aren't constant? and is there a way to prevent editing properties or values in future of code?
Asked
Active
Viewed 375 times
2
-
The `const` only applies to the variable itself. You cannot change the value of `sampleArray`, but you can freely modify the contents of the object it references. – Pointy May 12 '19 at 20:06
-
Thank you for replying. and Yes, I can see that I cannot re-assign value of constant. However I want to know how to make constant all values. It is just I can't do? If it is like just reference, that all :D – Seia May 12 '19 at 20:09
2 Answers
2
Constants in Javascript will prevent the variable reassigning but not on its properties.
const item = { foo: 0 };
item.foo = 1 // Works
item = { bar: 0 } // Error
If you want to prevent this you can use Object.freeze for objects
const item = { foo: 0 };
Object.freeze(item);
item.foo = 1; // Won't modify its property

l-portet
- 636
- 7
- 14
-
Constants in Javascript will prevent the variable **mutation** but not its properties. I think mutation and modifying are same. mutation means changing in properties. A better word may be assigning – Maheer Ali May 12 '19 at 20:15
-
2
What does const
mean?
If a variable is declared using const
keyword it means it can't be assigned to new value. It doesnot mean that you can't modify it. Changing the properties of object is modifying.
Solution
If you want an object not to change you can use Object.freeze()
let someObj = {};
someObj.prop = 1; //setting prop to '1'
Object.freeze(someObj); //after this line you can't modify object
someObj.prop = "changed"; //prop will remain '1'
console.log(someObj)
Note: Object.freeze()
is a shallow freeze means that if there are nested objects they can be still modified. Consider the example below.
const obj = {
upper:"something",
nested:{
nestProp:"this is nest prop"
}
}
Object.freeze(obj);
obj.upper = 'new' //can't be changed
obj.nested.nestProp = 'new' //will be changed
console.log(obj)
Now this problem can be solved using recursion.
function completeFreeze(obj){
Object.freeze(obj);
for(let key in obj){
if(typeof obj[key] === "object"){
completeFreeze(obj[key])
}
}
}
const obj = {
upper:"something",
nested:{
nestProp:"this is nest prop"
}
}
completeFreeze(obj);
obj.nested.upper = 'new' //will not be changed
console.log(obj)

Community
- 1
- 1

Maheer Ali
- 35,834
- 5
- 42
- 73
-
1It should be noted that `Object.freeze()` is a "shallow" freeze; it does not freeze the whole object graph. – Pointy May 12 '19 at 20:15
-
1