Tell us what’s happening:
Hey, I’ve been working this challenge for a while now and I managed to wrap my head around the .push function. My problem is with the Display code portion of the exercise. From what I can tell I’ve done what is required but it still prints out the last test is not met. What am I missing?
Your code so far
function nextInLine(arr, item) {
// Your code here
arr.push(5);
return arr.shift(); // Change this line
}
function nextInLine(arr, item) {
arr.push(1);
return arr.shift();
}
// Test Setup
var testArr = [1,2,3,4,5];
// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 10)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr[4]));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/stand-in-line
There should be one function, and this line in both of yours indicates the [conceptual] issue you’re having:
arr.push(1);
The point of a function is that it’s a reusable piece of code, you don’t write a function for every single possible value. For example, if I have a function that adds two numbers, I don’t do:
function add(a, b) {
return 0 + 0;
}
function add(a, b) {
return 0 + 1;
}
function add(a, b) {
return 1 + 1;
}
And so on for every possible number. That’s not how programming works (or algebra for that matter). Which function does the computer pick? In JS it will be the last one in the list, each function definition will override the previous one. And if it did work, there are infinite numbers so there would need to be an infinite number of functions.
Similarly, the item
that gets push
ed in this challenge can be anything, so what you would need to do is write a near-infinite number of functions, one for every possible value that can be represented in JS, of any type. Which is not how you solve the challenge.
So for that add
function, what I do is this:
function add(a, b) {
return a + b;
}
Now it works with any number.
Edit: the tests are there to check whether your code works. This is really important: the values the tests use are examples, the point is not to literally always return those values
Hey Dan, sorry its taken so long to get back to you. Though I understand the point you are making, and will be using it from now on, it has not cleared up my original issue concerning the last section of the exercise.
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 10)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr[4]));
The changes are placing the 10 and 4 in the assigned spots and returning 10.
Dan, after several attempts I finally realized I was taking the exercise too literally. Thank you for all your help!
1 Like