I am trying to make sure I understand the core concepts of this exercise and value the educational journey of each individual so I am posting here instead of on the facebook group.
This question pertains to stand in line lesson 165.
Here is the code:
------------------------------------------------------
function nextInLine(arr, item) {
// Your code here
arr = ["chicken", "turkey", "sausage"];
item = 1;
arr.push(item);
var removed = arr.shift(0);
return removed;
}
------------------------------------------------------------------------
// 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));
Why does the above not work, in comparison to the below:
(answer from the website)
function nextInLine(arr, item) {
// Your code here
arr.push(item);
var removed = arr.shift();
return removed; // Change this line
}
Not sure what you mean. But if you compare your code with the solution, you see that you have two extra lines:
arr = ["chicken", "turkey", "sausage"];
item = 1;
But arr and item are passed to the function as parameters. So no matter what you pass to the function it will always return the same, because you overwrite those values.
arr and item get their values by calling the function with certain parameters. E.g. running nextInLine([1,2,3,4],2) will run the function nextInLine and give arr the value of [1,2,3,4] and item the value of 2.
The only thing the tests do, is running the function with certain parameters and then check if the return value is what it should be.
I thought standard practice was to define variables first - like I said, it’s not about the answer…I’m trying to make sure I understand each concept.
The point of a function is to be a reusable bit of code. So for example if you want something that adds two numbers:
function add(a, b) {
return a + b;
}
You don’t write
function add(a, b) {
var a = 1;
var b = 2;
return a + b;
}
Because that completely defeats the point of using a function. If you do that, it then makes no difference if you’d like to add 4 and 5, the function will always just add 1 and 2.
The earlier challenges use global variables because it’s easier to understand for simple things: it means everything is explicit while you’re learning the basics. Once you’re past there, they aren’t good practice in 99.999999% of cases.
EDIT: you wanted to know where the values come from. There are a set of tests that run when you hit go. They run the function with different values, and check if each set of input values returns what was expected. The function should work for any value that matches the expected inputs