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?
2 Answers
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) 2 Comments
Object.freeze() is a "shallow" freeze; it does not freeze the whole object graph.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 
constonly applies to the variable itself. You cannot change the value ofsampleArray, but you can freely modify the contents of the object it references.