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,227
  • 4
  • 41
  • 58

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
  • 113,687
  • 23
  • 165
  • 188