0

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);
hong4rc
  • 3,999
  • 4
  • 21
  • 40
user310291
  • 36,946
  • 82
  • 271
  • 487
  • Because `a` in `test` function is a local variable to that function, and you're overriding the passed reference to the array `a` in the outer scope. – Teemu Mar 07 '22 at 10:42
  • but same as b no ? – user310291 Mar 07 '22 at 10:42
  • 1
    Not the same, you're accessing the reference `b`, not overriding it. Reference is also a value, passing a reference doesn't break the variable scope. – Teemu Mar 07 '22 at 10:43
  • @Ivar I know that, my question is more specific about array ;) – user310291 Mar 07 '22 at 10:46
  • @Teemu ok that should be the reason, now is there something in the spec or whatever that it was designed this way ? – user310291 Mar 07 '22 at 10:46
  • To avoid shadow variable, I renamed variable in `test` function to `c and d` – hong4rc Mar 07 '22 at 10:47
  • 1
    @user310291 An array is also an object. If you assign a new value to a variable that you passed as a parameter, you overwrite the parameter's value, not the original. – Ivar Mar 07 '22 at 10:47
  • @Ivar but b is same kind of array ;) – user310291 Mar 07 '22 at 10:48
  • 1
    @user310291 [Somewhere in the depths](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-parameter-lists), you've just to dig it out. – Teemu Mar 07 '22 at 10:51
  • 1
    @user310291 Both `a` and `b` are two separate arrays that you pass. The assignment operator assigns a new value to the parameter, but doesn't do so to the variable that you passed (`a`). This is because JS is pass-by-value. If you use `.push()` then you are performing modifications to the referenced array, with is the same as the one you passed if you don't reassign a value to `d`. This is what the duplicate (tries to) explain(s). – Ivar Mar 07 '22 at 10:54
  • @Teemu ok thanks I get it ;) – user310291 Mar 07 '22 at 10:55
  • @Ivar ok thanks you're right I now get it ;) – user310291 Mar 07 '22 at 10:56

1 Answers1

1

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);
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39