Task 7 : Strange Result in console.log


#1

So this is my code.. It works, but I don't know where the extra '29' is coming from the in the console.log:

var fortask = 5

for (fortask; fortask <24; fortask++) {
console.log(fortask+ " FOR");
}

while (fortask<30) {
console.log(fortask+" WHILE");
fortask++
}

This is what the console.log produces:
5 FOR
6 FOR
7 FOR
8 FOR
9 FOR
10 FOR
11 FOR
12 FOR
13 FOR
14 FOR
15 FOR
16 FOR
17 FOR
18 FOR
19 FOR
20 FOR
21 FOR
22 FOR
23 FOR
24 WHILE
25 WHILE
26 WHILE
27 WHILE
28 WHILE
29 WHILE
29

Anyone know where the '29' comes from? I added the "FOR" and "WHILE" to help track what each console.log is doing..


#2

it has nothing to do with the for or the while loop. The console has this feature to echo the last value in your code so if you enter 2+2 you'll see the result value of 4. So what you see here is just the value of fortask++. And in case you ask why you don't always see this, well no value is printed when there is no last value to be printed (undefined) and console.log happens to have no value.


#3

@jamesh777,
Directly after your while loop add a code-line

console.log("== End of Code ==");

#4

Thank you for the explanation!


#5

Thanks Leohard, that helped illustrate the point nicely.