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.
``` 1. A brief explanation of functions and array 2. Solving the question ```
An array is a special variable, whose length is not fixed [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) , and which can hold more than one value at a time - [Wikipedia](https://www.w3schools.com/js/js_arrays.asp) .
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
anditem
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
function nextInLine(arr, item) {
}
function nextInLine(arr, item) {
arr.push(item);
}
function nextInLine(arr, item) {
arr.push(item);
arr.shift();
}
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.
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](@dailydevtips) session at the Hashnode Technical Writing Bootcamp.