"Stand In Line" javascript problem question

"Stand In Line" javascript problem question
0.0 0

#1

I got this question correct but I don’t understand exactly how it works:

How was “testArr[]” updatd with the new values?

Since i’m just returning “item” and i’m not returning ‘arr’, how does “testArr” know its values were changed? I’ve operated on ‘arr[]’ using push() and shift() but never returned it.

You can see the contents of ‘testArr’ is ouput via the console after I call 'nextInLine()"

 function nextInLine(arr, item) {
  // Your code here
  
  arr.push(item);
 item = arr.shift();
  return item ;  // Change this line
}

// Test Setup
var testArr = [1,2,3,4,5];

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 10)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));

#2

You do not have to return arr. testArr is passed as a reference into the nextInLine function as the argument arr. It is the same as writing the function as follows:

 function nextInLine(arr, item) {
  testArr.push(item);
  item = testArr.shift();
  return item ;  // Change this line
}

#3

What i don’t understand is why does testArr[] adopt the values of arr? when I never declared testArr was equal to its reference arr.

Ex - I never did this in the function:

arr.push(item);
testArr = arr;

But somehow, testArr adopted the changes I made to arr

If I re-write this with variables that equal numbers, if I operate inside the function on one of the values passed into the function, the global declaration doesn’t change - example:

var num1 = 1;
var num2 = 3;

console.log("Pre call " + num1);

function addFive (a, b) {
  
  a = a + b;
  
  console.log("a: " + a );
  return a;
}

addFive(num1, num2);

console.log("Post call " + num1);

Does this make sense? I’m wondering why arrays seems to work differently than other variables I pass into a function


#4

A variable pointing to an array is a reference to it. When you pass an array, you’re copying this reference. Unless you make a duplicate (originalArray.slice(0)) then you only have a reference to the original. As far as javascript is concerned, arr that is passed into the function is the actual array, so any changes made to it are reflected in the original array.