Why is the console printing the number 3 after running my code?


Excercise link: https://www.codecademy.com/courses/javascript-beginner-en-qDwp0/0/3?curriculum_id=506324b3a7dffd00020bf661

Hi, so I'm kind of confused by the behavior of this code that I wrote on my own. It is working exactly as intended (printing the numbers 23, 81, 94, and 56 to the console) until it gets to the end of the code, where it seems to be printing the number 3, even though there is no console.log() instruction to do so. If someone could help me understand why it's doing that I would really appreciate it as it's kind of throwing me for a loop (no pun intended :wink:).


var junk = [23,81,94,56,"tomato","orange"];

var counter = 0
while(isNaN(junk[counter]) === false) {

Console output:



The 3 is the final value of counter and is a response from the command line interpreter and may be ignored. Since we are running our code in the console, everything we run is treated as a command line request. It's normal behavior for the interpreter to respond.

In terms of the code, there is room for refactoring. The old adage, "if it looks complicated, it probably is too complex." This code looks complicated. How could we simplify it?

var junk = [23,81,"tomato","orange",94,56];

var index = 0;
do {
    if (isNaN(junk[index])) continue;
while (index++ < junk.length);

Note there is no semi-colon after the while code block. You'll also notice there is no console echo this time. That is because the last executed command was console.log() so that was the final response.

Now I just need to test this in the lesson to see if it is what is expected. Checked and passed.


Hi Zac,
Just wanted to tack on a link to these two posts regarding your first question to @mtf's awesome answer in case you wanted to learn more about when the interpreter will return things like "3" and how you can avoid it if you so wish.