Tell us what’s happening:
When I looked at the problem, I broke it down into three steps:
- Add a number at the end, which is arr.push(item);
- Remove a number at the beginning, which is arr.shift();
- Return the previously removed number. If I do “return arr.shift();” it’ll just remove yet another number, and output 2.
For step 3, is there a way we can have it return the previously removed number? Or is the only way to combine steps 2 and 3? Feels not intuitive, as someone just starting out. It’s telling it “return it, but also remove it” instead of keeping it as two steps (is there ever a reason to have it remove it, then reference what was moved in a separate step, if even possible?)
Second question:
When it comes to arr.push(item) in the function, I was writing testArr.push(item) intuitively at first, which will be the same answer.
As someone starting out, I don’t see it as a huge concern, since I was on the right track in my thinking. However, if I was wanting to use this function for other arrays, I’d need to make sure to have it linked correctly.
When it comes to functions, “arr” and “item” are parameters within the function? And when we type out the code “nextInLine(testArr,6)”, what term is used to “connect” testArr & 6 to the “arr” and “item”? I’m going to take a guess and say… it’s parameters again. However, feel like I’m missing some words to be able to describe it. I understand testArr gets inputted as arr in the function. 6 gets inputted as item in the function.
Is there a good write up on this topic? I was starting to watch Harvard’s CS50, which has been really good so far.
Your code so far
function nextInLine(arr, item) {
// Only change code below this line
arr.push(item);
arr.shift();
return <something>
// Only change code above this line
}
// Setup
let 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/109.0.0.0 Safari/537.36
Challenge: Basic JavaScript - Stand in Line
Link to the challenge: