Pieter De Clercq
Pieter De Clercq

Reputation: 1971

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]

Upvotes: 0

Views: 203

Answers (2)

gurvinder372
gurvinder372

Reputation: 68443

It doesn't work because in the second snippet you changed the object (a primitive value) it was pointing to which had the local scope.

test = 8; // it is no longer pointing to the earlier object in memory so that object value has not changed, just that this reference is pointing to new object.

After this method a() was finished it lost the object which was in local scope and regained the one which was in outside scope.

If you want to change the value of test and while passing the value of the array then

var test = [5, 5];
function a(test) {
  test.splice(0,test.length);
  test.push(8)
}
a(test);
console.log(test);

This will first clear the test array and push 8 into it.

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

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

Upvotes: 1

Related Questions