Modifying array with shift and push

I don’t get this one, could someone please explain in detail. I understand arrays, push and pop and pull and all the rest but this one is causing my brain to do a burnout. Please help.

   **Your code so far**

function nextInLine(arr, item) {
 // Only change code below this line
arr.push(item);
var removed = arr.shift()
return removed;
 // Only change code above this line


}

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

// Display code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6));
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/91.0.4472.123 Safari/537.36

Challenge: Stand in Line

Link to the challenge:

Hello! Welcome to the community :partying_face:!

What is it that you don’t understand? shift? If so, it just removes the first element and returns it while also modifying the array in place, which means it has side effects.

In this case, whenever you call the nextInLine function, it modifies the array twice:

  1. When you push the item into the array
  2. When you remove the first element using shift.

Does it help?

3 Likes

Thanks, late-night brain fog. The next question actually put it into perspective. Thanks for your reply. Much appreciated.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.