Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript arrays passed by reference or value?

Tags:

javascript

I have a little confusion as to how arrays are handled when passed to functions. My question is why does the ouput of sample2.js NOT be null ?

// sample1.js======================================
// This clearly demonstrates that the array was passed by reference
function foo(o) {
  o[1] = 100;
}

var myArray = [1,2,3];
console.log(myArray);  // o/p : [1,2,3]
foo(myArray);
console.log(myArray); // o/p : [1,100,3]




//sample2.js =====================================
// upon return from bar, myArray2 is not set to null.. why so
function bar(o) {
  o = null;
}

var myArray2 = [1,2,3];
console.log(myArray2);  // o/p : [1,2,3]
bar(myArray2);
console.log(myArray2); // o/p : [1,100,3]
like image 498
runtimeZero Avatar asked Mar 14 '26 09:03

runtimeZero


1 Answers

Variables pointing to arrays only ever contain references. Those references are copied.

In bar, o and myArray2 are both references to the same array. o is not a reference to the myArray2 variable.

Inside the function, you are overwriting the value of o (a reference to the array) with a new value (null).

You aren't following the reference and then assigning null to the memory space where the array exists.

like image 71
Quentin Avatar answered Mar 15 '26 23:03

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!