2

node.js screenshot

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
  • 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. Commented May 12, 2019 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 Commented May 12, 2019 at 20:09

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

2 Comments

It should be noted that Object.freeze() is a "shallow" freeze; it does not freeze the whole object graph.
@Pointy Thanks for information. I have updated the answer.
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 

2 Comments

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
Yes, you're right it was not the proper term, I've edited it :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.