Stand in Line - Please help!

Tell us what’s happening:
Greetings, all!

I was able to complete the challenge and I understand how and why the code works.

Except for 1 part I’m having a hard time grasping…

console.log(nextInLine(testArr, 34));

Before: [1,2,3,4,5]
1
After: [2,3,4,5,34]

What I understand:
This makes perfect sense to me. The Function is being called and passing through the array “testArr” and the “item” of 34. This results in “1” being “shifted” out of “testArr” and “item” 34 being “pushed” (added) to the end of “testArr”.

What I don’t understand:

console.log(nextInLine([2], 34));

Before: [1,2,3,4,5]
2
After: [1,2,3,4,5]

I’m pushing or adding 34 still to the end of the array. Why doesn’t “After” show [2,3,4,5,34] like in my previous solution? What is [2] trying to say? Why would putting a [2] in the arr spot of the nextInLine() function even pass any information? Because from what I understand, the only valid array in this entire exercise is in the testArr variable. Am I just thinking too deep into this and freeCodeCamps JSON script is working something else behind the scenes? To be honest, I don’t really understand why any of these following lines passed without indicating a “testArr” when calling the function nextInLine:

nextInLine([], 5) should return a number.
Passed
nextInLine([], 1) should return 1
Passed
nextInLine([2], 1) should return 2
Passed
nextInLine([5,6,7,8,9], 1) should return 5
Passed
After nextInLine(testArr, 10), testArr[4] should be 10

Your code so far


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

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

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/stand-in-line/

OoOoOoohh! That makes complete sense now. Thank you so much for clarifying that. What a life saver. I think what I wasn’t understanding is that you can actually pass through made up arrays through the function!! I guess that’s technically what “testArr” is doing. Except you’re using the variable to pass it instead of just plopping it up there, lol.

So if I’m understanding correctly:

function nextInLine(arr, item) {
arr.push(item);
return arr.shift();
}

console.log(nextInLine([300,400,111,999], 34));

Should return:
300
[400,111,999, 34];

Edit: tested in dev console. It does indeed return 300. Thanks again!

1 Like