netuser
netuser

Reputation: 553

Array getting reset in function

Scenario 1

var a = [1, 2, 3];

function isChanged(a) {
  a = [];
}
isChanged(a);
console.log(a);

Scenario 2

var a = [1, 2, 3];

function isChanged(stack) {
  while (stack.length != 0) {
    stack.pop();
  }
}
isChanged(a);
console.log(a);

Why is the array not empty in the first function, but it is empty when I use the second one?

Edit :

I played around the changing the variable by assignment, and overriding its property.

Scenario 3 - changing the property of object

var a = {
  prop: "Stackoverflow"
}

function change(a) {
  a.prop = "stack"
}
change(a)
console.log(a)

Scenario 4 - changing the whole variable itself

var a = {
  prop: "Stackoverflow"
}

function change(a) {
  a = {
    "prop": "stack"
  }
}
change(a);
console.log(a);

Upvotes: 1

Views: 557

Answers (2)

Michael Geary
Michael Geary

Reputation: 28880

In the first example, when you set a = []; you are only changing the local variable a, which (after the assignment) no longer has any relation to the global variable that happens to have the same name. In the second example, you are directly modifying the stack variable, which happens to be the same object as the global variable a. If you were to do stack = whatever, it would behave similarly to the first example.

Upvotes: 1

Eric Lovell
Eric Lovell

Reputation: 1

My guess is because in the first a is an object reference, which is set to a new empty array. Where as the 2nd calls a function on that object reference, which will actually remove elements from the array you pass to your function.

Upvotes: 0

Related Questions