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 the array.
The
nextInLine
function should then return the element that was removed.Brief Summary
1. A brief explanation of functions and array
2. Solving the question
A brief explanation of functions
An array is a special variable, whose length is not fixed MDN , and which can hold more than one value at a time - Wikipedia .
A function is a set of instructions compiled into a block of code. Everything in the block of code will be executed when you call the function.
Solution:A breakdown of the question
- Write a function, with
arr
and item
as parameters- Add the number to the end of the array
- Remove the first element of the array
- Return the element that was removed from the array
Write a function, with arr
and item
as parameters
function nextInLine(arr, item) {
}
Add the number to the end of the array
function nextInLine(arr, item) {
arr.push(item);
}
Remove the first element of the array
function nextInLine(arr, item) {
arr.push(item);
arr.shift();
}
Return the element that was removed from the array
function nextInLine(arr, item) {
arr.push(item);
return arr.shift();
}
Calling the function with an argument of [2]
and 8
, returns 2
.
I screenshot the image below from my Console.
The wrong answer that kept me stuck for a while
function nextInLine(arr, item) {
arr.push(item);
arr.shift();
return arr.shift();
}
By writing this code this way, I thought the code will return the removed element of the array, but it gives a wrong answer because the code simply interprets that the removal of the first element of the array took place twice. Hence, removing the first element, which will make the former second element to be the first element, removing the former second element, and returning the recently removed value.
Looking at this question now, I feel embarrassed to have found this question difficult some time ago. I really hope it is useful to some people who need help with finding the solution to this question.
I am not yet done with my exercises on freecodecamp, so I will be updating this series as I figure more questions out.
Thank you for taking out your time to read this article. I look forward to getting feedback from you.
This article was inspired by Chris Bongers session at the Hashnode Technical Writing Bootcamp.