Freecodecamp: Basic Javascript: Stand In Line Question

Freecodecamp: Basic Javascript: Stand In Line Question
0

#1

Hey guys, for the Stand In Line exercise, I was able to solve it, but had a few quick questions.

The exercise:

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.

My solution:

function nextInLine(arr, item) {
  
  arr.push(item);
  var arr = arr.shift();

  return arr;  
}

my original answer was:

function nextInLine(arr, item) {

arr.push(item);
arr.shift();

return arr.shift();
}

How come my original answer does not work and I have to set var arr? How come return arr.shift(); does not work?

Thanks a lot!!


#2

Your original solution uses shift twice. The first time, the first item (the number 1) is removed. The second time, the next item (the number 2 - which is now the first) is removed and returned by the function.

P.S. Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.


#3

Thank you!

And yes, I will remember to do that. This is my first post here so sorry about that!


#4

No worries. Just trying to prevent spoilers.


#5

huh array tell me the length after created a variable return value?

let testArr = [1,2,3,4,5];
function nextInLine(arr, num){
     arr.push(num);
    console.log(arr);   
}
function nextInLine2(arr, num){
     var newArray = arr.push(num);
    console.log(newArray);   
}
nextInLine(testArr, 18)
> (6) [1, 2, 3, 4, 5, 18]
let testArr2 = [1,2,3,4,5];
nextInLine2(testArr2, 19)
> 6

I have created a new variable for newArray to make it length instead of showing the whole array. I do not understand both are different result. For example if I have created


#6

found this probably help you understand return value better…
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_push_return