3

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]
1
  • By reference. Only primitive types passed by value. Commented Jul 24, 2014 at 12:00

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

0

An visual example of what Quentin said many years ago. In other words, references to arrays create new arrays, but the new arrays contain references to the original array's values.

function updateArray (arrayOfRefs) {
      let arrayInternal = arrayOfRefs;
      arrayInternal[1] = 100;  // or a value like null
      arrayInternal = null;  // null this reference array (not the external original)
      arrayOfRefs[1] -= 1;  // proves both refs were to same external value
      arrayOfRefs[2] = null;
}

var externalArray = [1,2,3];  console.log(externalArray);
updateArray (externalArray);  console.log(externalArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.