Reputation: 553
var a = [1, 2, 3];
function isChanged(a) {
a = [];
}
isChanged(a);
console.log(a);
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.
var a = {
prop: "Stackoverflow"
}
function change(a) {
a.prop = "stack"
}
change(a)
console.log(a)
var a = {
prop: "Stackoverflow"
}
function change(a) {
a = {
"prop": "stack"
}
}
change(a);
console.log(a);
Upvotes: 1
Views: 557
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
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