Basic JavaScript: Stand in Line explanation

function nextInLine(arr, item) {
  // Your code here
  arr.push(item); //adds the number to the end of the array
  var removed = arr.shift();//removes the first element of the array
  return removed;  // Change this line
}

// 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));

Guys hi, you know this exercise in the basic javascript part. However, I could not manage to understand what this code does. Could someone explain the basic structure of it?

Thank you already.

2 Likes

Hi @bmakas06,

In of itself, this exercise is not a difficult one to understand. I will try to break it down to help make it clearer.

  1. The method nextInLine has two arguments : arr, which is an Array, and item, which is an element we want to add to the array.
  2. It first adds the item argument to the array. When adding elements to the array using the push method, elements are added to the end of the array.
  3. It then removes the first element of the array using the shift method. The shift method modifies the array and removes the first element from it. Meaning, for var testArr = [1,2,3,4,5], it will return 1 and the array will be testArr = [2,3,4,5]
  4. At the end we return the removed array element that was at index 0.
function nextInLine(arr, item) {
     arr.push(item); //2
     var removed = arr.shift();   //3
    return removed;   //4
}

Hope that helps.

3 Likes

Thanks a lot helped a lot :slight_smile:

how can I see/understand what value “arr” and “item” have.

They’re the array and item that are passed to the func when it’s called. One thing you can do to see them is log them inside the function before doing anything else.

Let me know if this helps here

with log do you mean “console.log”

function nextInLine(arr, item) {
// Your code here
arr.push(item);
var removed=arr.shift();
return removed; // Change this line
}
// Should I console.log them from here ? If so what would that be called in coding. Maybe “console.log(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));