0

By js convention and as far as I know

  • Primitive datatypes are worked under pass by value and
  • complex datatypes are worked under pass by reference

If it so

var ary = [1,2,3];
var dupAry = ary;
//Now I am going to rewrite the ary variable as follows
ary = [3,4,5];

Now I log the values of ary and dupAry it logs different values. By its standard both array should return the vaues.

  1. so why it return different array values?

Another scenario

    var ary = [1,2,3];
    var dupAry = ary;
    //No I gonna apply splice method to the ary.
    ary.splice(0,1);

Now both array return same values and it works fine with its standard.

  1. Finally why its doesn't applied with first scenario?
Benny
  • 2,250
  • 4
  • 26
  • 39
  • http://stackoverflow.com/questions/6612385/why-does-changing-an-array-in-javascript-affect-copies-of-the-array – Tuhin Aug 11 '16 at 07:57
  • When you make `ary = [3,4,5];`you assign a new array to ary and break the referral between `ary` and `dupAry` – Redu Aug 11 '16 at 08:11

2 Answers2

3
var dupAry = ary;

This assigns a reference to the array that ary points to to dupAry. Both ary and dupAry now hold a reference which points to the same array object. If you now assign something else to ary, then dupAry will continue to hold a reference which points to the array object, and ary will now hold some other value.

By assigning something to a variable, you're not modifying the object that variable already holds; you're modifying the object reference that variable holds.

ary.splice(0,1)

This modifies the actual object that both variables points to, so both see the change.

deceze
  • 510,633
  • 85
  • 743
  • 889
1

When you do this:

ary = [3,4,5];

... you aren't altering an array: you are destroying the previous reference and creating a brand new variable* with a brand new array. See the difference with:

ary.push(99);

(*) Well, not really a new variable, of course—I didn't know how to word it.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360