Why console.log(a) doesn't return same result [1, 2, 3, 4] as console.log(b) ?
function test(c, d) {
c = [1, 2, 3, 4];
d.push(4);
}
a = [1, 2, 3];
b = [1, 2, 3];
test(a, b);
console.log(a);
console.log(b);
Why console.log(a) doesn't return same result [1, 2, 3, 4] as console.log(b) ?
function test(c, d) {
c = [1, 2, 3, 4];
d.push(4);
}
a = [1, 2, 3];
b = [1, 2, 3];
test(a, b);
console.log(a);
console.log(b);
With a = [1, 2, 3, 4];
you are overriding the argument (which is local to the function) you have passed into the function test
. You are not making any changes to the actual array a
.
Now the a
inside does not even point to the array a
outside.
But there is a change happening when you do b.push(4)
, which actually mutates the b
array outside.
function test(a, b) {
a = [1, 2, 3, 4];
b.push(4);
}
a = [1, 2, 3];
b = [1, 2, 3];
test(a, b);
console.log(a);
console.log(b);