In javascript, why doesn't the list update with a variable?
var x = 5;
var l = [x];
x += 6;
why is l
still 5 and not 11? Is there a way to get it to update with the variable?
In javascript, why doesn't the list update with a variable?
var x = 5;
var l = [x];
x += 6;
why is l
still 5 and not 11? Is there a way to get it to update with the variable?
5 Answers
Reset to default 3l
is a list of values, not a list of pointers. To simulate what you're trying to do, you could store mutable objects and mutate them.
var x = { val: 5 };
var l = [x];
x.val += 6;
console.log(l); // [{ val: 11 }]
Unlike objects, primitive values are immutable. Once you change them you have to assign them back.
var l = [x];
x += 6;
var l = [x]; // new value updation.
Since you don't hold the reference to array, assigned back with a new array.
If you hold a reference to the array, you can just update the variable instead of whole array.
var arr = [x];
var l = arr;
x += 6;
arr[0] = x; // new value updation at position 0.
My understanding is that this is actually very simple:
Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object.
Changing the value of a variable never changes the underlying primitive or object, it just points the variable to a new primitive or object.
However, changing a property of an object referenced by a variable does change the underlying object.
only way to update array value is to reassign it.
A variable won't update itself. You have to redefine it.
var x = 5;
var l = [x];
x += 6; // x has changed but l has not, because you defined it to be old x
l = [x] // redefine it to be new x
console.log(l);
var x = 5;
x +=6;
var l = [x];
With this var l will be up to date