0

I'm a beginner learning loops.

I made a for loop like this:

for (i = 0; i < 5; i++) {
    console.log("Counting...");
}

As expected I get the output "Counting..." five times.

I modified the loop and put the counter inside it instead (maybe you shouldn't do this, I'm just trying things out).

for (i = 0; i < 5;) {
    console.log("Counting...");
    i++
}

Now i get:

Counting...
Counting...
Counting...
Counting...
Counting...
4

Where is this 4 coming from? What does it mean?

3
  • There is no 4 that gets printed: fiddle. You must have another console.log somewhere after.
    – sp00m
    Commented Jun 3, 2014 at 7:59
  • You should have got "Counting..." five times followed by an undefined in the first case?
    – Bergi
    Commented Jun 3, 2014 at 8:01
  • work fine in chrome, I do not see 4
    – jhyap
    Commented Jun 3, 2014 at 8:01

1 Answer 1

2

You probably are runnig this in Developer Tools or similar. "4" isn't actually printed, it's the return value of the last statement from the for loop.

When you ran your first loop, you probably saw this:

Counting...
Counting...
Counting...
Counting...
Counting...
undefined

(undefined is a return value in first case, because console.log() does not return anything). In second case, undefined is being replaced by 4.

2
  • Thank's, this clears it up. I didn't see any 'undefined' being printed out on Codeacademy where I'm doing this, maybe they strip it out. When I put my first loop in my own console, I did get undefined.
    – Johan Dahl
    Commented Jun 3, 2014 at 8:02
  • This is added as a convienience in development. To quickly evaluate some expression, you only have to type "2 + 5" and not "console.log(2 + 5);"
    – kamituel
    Commented Jun 3, 2014 at 8:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.