Can someone explain the .shift and .push in this function? [Spoiler]

I am up to “Challenge” 172 and I’m completely lost.

I searched online and found the solution, but I do not understand how it even works, I know that the .push removes the first item from the front of the array, and .shift adds an item, but why does it return the next number in the sequence?

Can someone explain? Do I need to start all of the Javascript Challenges over??? Does this start making sense soon???

Here are the instructions:

**Stand in Line
In Computer Science a queue is an abstract Data Structure where items are kept in order. New items can be added at the back of the queue and old items are taken off from the front of the queue.

Write a function nextInLine which takes an array (arr) and a number (item) as arguments. Add the number to the end of the array, then remove the first element of array. The nextInLine function should then return the element that was removed.**

Here is the code:

function nextInLine(arr, item) {
var firstItem = arr.shift(arr);

// Your code here

return firstItem; // Change this line

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

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

Not quite…

array.push() adds whatever is in the parenthesis to the end of the array you specify.

Similar array methods are:

  • array.pop() - which ‘pops’ the last element off the array
  • array.shift() - which removes the first element from the array
  • array.unshift() - which adds whatever is in parenthesis to the beginning of the array.

I actually find that naming pattern really difficult to remember, and I look it up every time! I can remember push and pop, but shift and unshift doesn’t stick for me. I wish JS used words like append or prepend instead, since that makes more sense to me…but c’est la vie!


Well I screwed that up, but I’m still completely lost as to what that code up there is even doing! It seems like it has something to do with those last 3 console.log lines, but I really don’t understand what they are doing. . .

Here’s a commented version of the working function, line by line. I ignored the testing items underneath, but I can explain those to you if you like?

function nextInLine(arr, item) {  
  arr.push(item);   // this adds the value of 'item' to the end of the array
  var firstItem = arr.shift(arr); // this creates a variable that contains 
                                 // the first element in the array, 
                                // whilst also removing that item
  return firstItem;  // this returns the element from the array we just removed