Stand in Line - why initial solution doesn't work, explanation of 'removed' variable value assignment with .shift()

Hey All I was just wondering why my initial ‘solution’ didn’t work.
Here’s my thought process:
I use return arr[0] to return what I’m about to shift off - the challenge says to return the element that was removed (perhaps by the end of my function I have changed what arr[0] is?)
then I push the number being added (item) onto the array arr
then I shift off the first item of the array with arr.shift(). What’s wrong with that? - does this last procedure interfere with my first return procedure?

Also with the actual solution (hidden in the multi line comment), how does arr.shift() define the variable ‘removed’ with the value of the removed element? I thought all .shift() did was pop off the first element, so shouldn’t arr.shift(), if arr = [1,2,3,4] give [2,3,4]? I’m missing something here.

function nextInLine(arr, item) {
  return arr[0];

  var removed = arr.shift()
  return removed;*/


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

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // 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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36.

Link to the challenge:

Read the specification of the methods carefully. Shift returns the removed element, not the modified array(i.e. just trivia, careful, Push returns the length of the modified array). Also, when you return from a functions, it’s over :slight_smile:. The thread of execution won’t execute anything else in the function after the return statement.

1 Like