Whats wrong on my code? in Stand in Line1

Whats wrong on my code? in Stand in Line1
0

#1

Tell us what’s happening:

Your code so far


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));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.54.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/stand-in-line/


#2

Push isn’t doing what you think it’s doing

You’re right in thinking it adds an element to the array, however it doesn’t return the array, it just returns the length of the new array which is a number

Therefore shifting a number doesn’t work


#3

The following line is not doing what you think it is.

var array = arr.push(item);

The push method has a return value and the value return from it is a number representing the new length of the array after the push is executed. So, your code above pushes the item onto the end of arr, but assigns the value 6 to array. Then you attempt to use the shift function on array, but since array is just a number, your code errors out.

EDIT: @gebulmer We both responded at the same time with the same explanation. :smile: