Stand in Line Code Order Questions

Stand in Line Code Order Questions
0.0 0

#1

I was able to get the main gist of the challenge the only thing that I am confused on is that it seems the only way to get a complete on this task was to have your code written like:

function nextInLine(arr, item) {
// Your code here
arr.push(item);
var front = arr.shift();
return front; // Change this line
}

I originally had my variable (var front) above arr.push(item); and was not getting the complete pop up. It was not until I went to the get a hint section and saw that it had arr.push(item); above the variable.

Could someone explain why this order seems to be important?

Thanks in advance.

Phil Campbell


#2

The reason the order was important, is in the following test case, the reversed order solution would have return undefined instead of the correct answer 1

nextInLine([], 1);

Why? Because if you use shift() on an empty array, it returns undefined. See here for more information about the shift function. You would still be pushing the number 1 into testArr, but the return value of undefined gets assigned to the front variable (which is ultimately returned).


#3

Thanks for the explanation and the link to more detailed description.

Just going forward would it be a good idea to never have shift() first if there are going to be more elements manipulating an array?

I’m still kind of new to JavaScript and am still trying to get a better handle on code order making and breaking code.

Thanks


#4

There are no hard and fast rules for this, because it really depends on your overall application logic. You could still solve the challenge with the shift first, but you would need to add some additional logic to deal with unique case where the array was empty. For example, you could also solved this challenge like:

function nextInLine(arr, item) {
  // Your code here
  var front = arr.shift();
  arr.push(item);
  if (front === undefined)
    return item;
  else
    return front;
  // Change this line
}

#5

Thanks for the extra explanation, I will keep this in mind going forward.

Thanks for your assistance.