Whats wrong with this code?

Whats wrong with this code?
0

#1

only one test seems to be passing, passing empty array gives NaN

function nextInLine(arr, item) {
  // Your code here
  var remove;
  arr[(arr.length)-1]=+ item;
  remove=arr.shift();
  return remove;
    // 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));

#2

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.


#3

If you have to add items to an array, use .push().


#4

It’s not very clear what you’re trying to do, therefore it’s hard to know what is wrong.

I assume this is a challenge from FCC, but without the name, it’s hard to find the specific challenge. So very least you could do is briefly explain what you are trying to accomplish with nextInLine, so that people know what the function is supposed to do.

I’m guessing what went wrong is this line

arr[(arr.length)-1]=+ item;

you are setting the last element of the array to a numerical representation of item.

you probably needed to do

arr.push(item);

but I can’t be sure because I’ve no idea what the goal of the function is


#5

However, I’d highly suggest using something like repl.it to debug your code before you just simply throw out a piece of code and ask what is wrong. For the most part, people are nice enough to walk through the code and help you with these, but you gain nothing if you don’t know how to find what’s wrong with your code.

Track the change of variable by logging it to the console with console.log() and see if it’s what you expect after a certain piece of code. For example, put in console.log(arr) before and after arr[(arr.length)-1]=+ item; would have help you track the changes to arr.

Most of the codes in the algorithm challenges can be debugged this way, and you’ll usually find what went wrong.

If you done your debugging and still cant find what’s wrong, then you can tell people what you’ve done and that’d save them a lot of work in trying to help as well.