2

var x = [1, 2, 3, 4, 5, 6];

function change1(y) {
  y[0] = 7;
  y[1] = 8;
  y[2] = 9;
  y[3] = 10;
  y[4] = 11;
  y[5] = 12;
}
change1(x);
console.log(x);

var z = [1, 2, 3, 4, 5, 6];

function change2(y) {
  y = [7, 8, 9, 10, 11, 12];
}
change2(z);
console.log(z);

Output:

7,8,9,10,11,12 1,2,3,4,5,6

I am unable to understand in the above code why the change1() function can alter the passed array while the change2() function cannot.

And why is the line break not working?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Newline break should work if you were writing to the console. Since you are writing to the document/browser it will interpret it as HTML - try using a html newline `
    `
    – Jonathan Irwin Jan 16 '18 at 10:33

1 Answers1

15

y[..] = ... is modifying an existing object. That change is visible to anything that holds a reference to that object.

y = ... assigns an entirely new value to the local y variable and discards the previously assigned object reference. That change is not visible outside the function since nothing else has access to the y variable.

deceze
  • 510,633
  • 85
  • 743
  • 889