0

In this block of code the result will be "unll" for the first console and an empty array for the second console

function fn(o) {
o = null;
console.log(o); //console o
}
var x = [];
fn(x);
console.log(x); //console x

but in this block of code

function fn(o) {
o[0] = null;
console.log(o); //console o
}
var x = [];
fn(x);
console.log(x); //console x

when i access the first element of the array the result of both consoles is an array with null value in the first element.

And this is really confusing for me, i understand that in the first block of code the array was passed by value, so it didn't affect the x array.

but why in the second block it was passed with reference!!

So does anyone has an explanation please?

  • I'm sure there's a duplicate, but when you do `o[0] = null` you *modify the array object* that is stored in `o`, but when you do `o = null` you *change which value* is stored inside `o`. – apsillers Mar 20 '17 at 15:31
  • http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language – epascarello Mar 20 '17 at 15:31
  • Arrays (and other objects) are always passed by reference in JS. – skyline3000 Mar 20 '17 at 15:37
  • The pointer/reference to the array is passed by value - and so a change is not reflected. "Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function". See https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions – gus27 Mar 20 '17 at 15:43

0 Answers0