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?
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.
var l = [x += 6] would be a short-hand way of doing this, too.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.