2

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 5

3

l 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 }]
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

var l = [x += 6] would be a short-hand way of doing this, too.
2

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.

Comments

0

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);

Comments

0
var x = 5;
x +=6; 
var l = [x];

With this var l will be up to date

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.