Stand in Line (JS)

Stand in Line (JS)


Why this code is not working? Why I cannot use the var array?

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

var testArr = [1,2,3,4,5];

console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); 
console.log("After: " + JSON.stringify(testArr));


Check out what the Array.push() function returns here:


I read this article but I don’t understand where is the wrong
And my question about var array


Ok - so the push method doesn’t really work how you are assuming.

When you call arr.push(item) you push item into the end of arr. BUT then push function also returns the new length of the array, which you assign to the variable array.

Try console.logging the array variable in your function. Keep in mind you then call shift() on this variable


There is an example in the previous article:

var sports = ['soccer', 'baseball'];
var total = sports.push('football', 'swimming');

Why this example work and my code not work. It is the same:

var array = arr.push(item);

P.S. The array variable contains the new length of the array


That code does “work” in the sense that it executes. total in your example is equal to 4. I think you are making an assumption that total is ['soccer', 'baseball', 'football', 'swimming'] but it is not.


Yes, I think that total = ['soccer', 'baseball', 'football', 'swimming'] But, you say that total = 4 (length of the array)?


exactly. Total = 4 (the length of the array). because the .push() method returns the length of the array.

So in the Stand In Line problem you set var array = 4
then try var itemTest = 4.shift() and you’ll get an error (as the shift method doesn’t exist on the number prototype)


Thank you. I’m dummy. I thought that sentence “and returns the new length of the array” is addition that is secondary (( I thought that this method returned new array…


No problem. Happy coding :slight_smile: