1

In JavaScript, when I add variables to an array and then update each element in the array, why does the variable have the same value when output in the console?

In the below I would expect all variables to show 777 in the console but they show 0.

When the array is logged [777,777,777] is shown as expected.

var number1 = 0;
var number2 = 0;
var number3 = 0;

var numbers = [number1, number2, number3];

function updateNumbers() {
  var i;
  for (i = 0; i < numbers.length; i++) {
    numbers[i] = 777;

    console.log(numbers);

    console.log(number1);
    console.log(number2);
    console.log(number3);
  }

}

updateNumbers();

1
  • 3
    Because number1 and numbers[0] are not the same variable. Commented May 9, 2018 at 21:01

1 Answer 1

2

when you create your array you are passing the variables by value, not a reference to the variable.

var a = 1;
var b = 2;
var c = 3;
var test = [a, b, c];
console.log(test);

you can do what you want (sort of), but you need to use objects.

var a = {
  value: 1
};
var b = {
  value: 2
};
var c = {
  value: 3
};

var test = [a, b, c];
// test[0] refers to a
// test[1] refers to b
// test[2] refers to c

function updateNumbers() {
  var i;
  for (i = 0; i < test.length; i++) {
    test[i].value = 777;
  }
}

updateNumbers();

console.log(test); // this wont output like in your example
console.log(a.value);
console.log(b.value);
console.log(c.value);

Sign up to request clarification or add additional context in comments.

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.