1

Given this two arrays a and b:

var a = [1,2,3];
var b = a;
a.push(4);

console.log(b); /* [1,2,3,4]  */
console.log(a); /* [1,2,3,4]  */

Why isn't b equal with [1,2,3] ?

que1326
  • 2,040
  • 4
  • 36
  • 54

1 Answers1

1

The variable b holds the reference to array a. You need to copy the array instead use Array#slice method to copy.

var a = [1, 2, 3];
var b = a.slice();
a.push(4);

console.log(b);
console.log(a);
Pranav C Balan
  • 110,383
  • 23
  • 155
  • 178