You probably have already read a fair bit about some of this, but I’ll include as much as possible so that it’s a self-contained explanation.
push()
is a special method available to an array, which takes an item and adds it to the end of an array, it works as follows:
const arr = [0, 1, 2];
arr.push(3);
console.log(arr) // Prints [0, 1, 2 3] to the console
It is worth noting, because it’s a common mistake, is to assign the output of push()
to a variable, thinking that it’s an array:
const arr = [0, 1, 2];
const newArr = arr.push(3);
console.log(newArr); // Prints 4. *Not* an array!
console.log(arr); // Prints [0, 1, 2].
As you can see, the push()
method actually returns the length of the new array, instead of the array itself. In addition, it is important (for later) to keep in mind that the push()
method actually mutates the original array (arr
in our example is changed).
shift()
works by removing the first item in the array:
const arr = [0, 1, 2];
arr.shift();
console.log(arr); // [1, 2];
And the return value of the shift()
method is the value of the item that has been removed:
const arr = [0, 1, 2];
const brr = ['Nya', 1, 2];
const a = arr.shift();
const b = brr.shift();
console.log(a); // Prints 0.
console.log(b); // Prints 'Nya'.
console.log(arr); // Prints [1, 2];
console.log(brr); // Prints [1, 2];
Now let’s have a look at the function that you posted, paying attention to the additional comments:
function nextInLine(arr, item) {
// Your code here
// arr = [1, 2, 3, 4, 5], item = 6;
arr.push(item); // This push 6 into arr
// arr = [1, 2, 3, 4, 5, 6], item = 6;
var removed = arr.shift(); // This removes the first item in arr **AND** assigns the return value (value removed) to the variable removed
// arr = [2, 3, 4, 5, 6], item = 6, removed = 1
return removed; // Change this line
}
So when you call the function nextInLine
on the array [1, 2, 3, 4, 5]
, testArr
becomes [2, 3, 4, 5, 6] and 1
is returned, that is:
var testArr = [1,2,3,4,5];
console.log(nextInLine([1, 2, 3, 4, 5]); // Prints 1
console.log(testArr); // Prints [2, 3, 4, 5, 6]
One other thing that is perhaps worth mentioning here is that testArr
is passed into the function as a reference—therefore any changes that you make to arr
inside the function, which is a reference to testArr
declared outside the function, will change it.
I hope that helps! 