Noob Question about Stand In Line Challenge

The challenge in question is here - https://www.freecodecamp.org/challenges/stand-in-line

Here is the answer that worked:

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

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

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));

Originally I was trying this:

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

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

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));

Shouldn’t I have to used the testArr instead of arr because it has the values I need to apply to my function inside of it? Not sure if I am properly explaining what I’m asking but I’m just wondering why I wasn’t allowed to use the testArray underneath. Thankyou!

You are far from the only person to be confused by this @jasonread241. See there are two kinds of functions, pure, and impure.

A pure function only performs operations on parameters passed into it, while impure functions reach outside of their scope (i.e. closure). Your initial attempt would be an example of an impure function, because you would have altered the array stored in the testArr variable outside of the functions scope.

I know it is difficult to see, but the example does have it setup that the testArr is being passed in as the first parameter. The line is nested between the two console.log() statements. It is pretty hard to see, let alone understand.

1 Like

Makes perfect sense now thankyou! Working through this and being able to use the forum for help is definitely making the task of learning js seem less daunting now.

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

1 Like

Thanks for that I’ll make sure to use that next time :slight_smile:

Just to clarify further. The reason the challenge failed was because the third test run is

nextInLine( [5,6,7,8,9] , 1)

It doesn’t pass testArr to the function nextInLine().

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

So when the third test runs using your original try:

  var removedItem = **testArr**.shift();
  return removedItem;  // Change this line

It is removing [ 1 ] and returning it. The test expects 5 and fails. :beers: