3

I have the following code for Ecma-Script-6 template constants.

const person = 'John Smith';
console.log(person);

person = 'Naeem Shaikh';    
console.log("{{After changing the value for person.name}}");

console.log(person);

of-course it doesn't work. http://www.es6fiddle.net/i3vhumdx/ It gives following error,

person is read-only

now the same thing i do with an object.

const person = {name: 'John Smith'};

console.log(JSON.stringify(person));

person.name='Naeem Shaikh';
person.age="24";

console.log("{{After changing the value for person.name}}");

console.log(JSON.stringify(person));

http://www.es6fiddle.net/i3vhzblm/

Output is:

{"name":"John Smith"}
{{After changing the value for person.name}}
{"name":"Naeem Shaikh","age":"30"}

here I am able to write into a read-only object without any problem. Can anyone explain this behavior.

Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88

1 Answers1

3

You would have the same behavior when changing the argument passed to a function from inside that function : if it's a string, the external one isn't changed, if it's an object and you change a property, it is changed.

The point is what the value of a variable is :

  • for an object, it's a reference to the object, you don't change that reference
  • for a string, it's a reference to the string, which happens to be immutable

When you're changing the properties, you don't change the value (the reference to the object).

An extract of the MDN :

// const also works on objects
const myObject = {"key": "value"};

// However, object attributes are not protected,
// so the following statement is executed without problems
myObject.key = "otherValue";

What you seem to want is to have a constant immutable object. Freeze it :

const person = Object.freeze({name: 'John Smith'});

This way it wouldn't be possible to change the name of the person.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • http://www.es6fiddle.net/i3vi7or9/ I am not changing the reference here in this fiddle right? but it works like a constant – Naeem Shaikh Dec 19 '14 at 12:01
  • Your assigning a new value to the person variable : you try to make it refer to another object. – Denys Séguret Dec 19 '14 at 12:02
  • ok so `reference` and `freeze` is the key words here.. Bcoz of having a reference value object would behave a little different as a constant and To overcome it we should freeze it. do I get it now? – Naeem Shaikh Dec 19 '14 at 12:06
  • I think you get it. Be careful (in more complex cases) that freezing isn't recursive (it doesn't freeze properties of property values when they're not immutable). – Denys Séguret Dec 19 '14 at 12:08