0

I'm trying to do something like this:

var obj={o:"a string"};
var o=obj.o
console.log(o)
o='modified'
console.log(o)
console.log(obj.o)

The result is:

a string
modified
a string

But I expect it to be:

a string
modified
modified

I tried destructuring too without success: it seems that the property and the variable are not linked.

Is there a way to link o to obj.o ? I don't want to use obj.o to modify obj property, but o instead.

Thank you in advance for your help.

Alphapage
  • 901
  • 1
  • 6
  • 29

1 Answers1

5

No, you can't "link" variables and object properties.

If the o property was a reference to an object, it would work:

var obj = { o: { foo: 'bar' } };
var o = obj.o;
o.foo = 'baz';
console.log(obj.o.foo); // 'baz'

Primitives however are copied, you can't get a reference to a string. When you read the value of the property o of the obj, the value is copied, because it's a string, and you get a new string which is not related to the old string in the object.

When you assign the new string to the variable, the old string value is lost (at least for the variable o).

PeterMader
  • 6,987
  • 1
  • 21
  • 31