thepieterdc thepieterdc - 7 months ago 22
Javascript Question

JavaScript global variable not changed

Why can I add something to a global declared array, but not change the value of the variable itself?

This works:



var test = [5, 5];
function a(test) {
test.push(8);
}
a(test);
console.log(test);
//expected: [5, 5, 8]





But this doesn't:


var test = [5, 5];
function a(test) {
test = 8;
}
a(test);
console.log(test);
//expected: 8 but is [5, 5]




Answer

In your second code, you are passing a the reference of your array object as an argument to the function a. And you are cutting off the reference's connection inside of that function by assigning a new primitive value to the variable which holds the reference. Hence the array in the global scope won't get affected at all.

This case is similar to,

var x = [];
var y = x; //setting the reference of the object x to y
y = 10; //cutting off the connection to the reference.

console.log(y); //10
console.log(x); //[]

If you do not replace the reference with a primitive value then,

var x = [];
var y = x; //setting the reference of the object x to y
y.push(10);

console.log(y); //[10]
console.log(x); //[10]
console.log(x == y); //true

Basically using a value in global scope would cause unnecessary conflicts. Still if you want to achieve what you want to do, then remove the parameter of the function a.

var test = [5, 5];
function a() {
  test = 8;
}
a();
console.log(test); //8
Comments