Dhanu AT
Dhanu AT

Reputation: 39

extra output after loop

I am learning JavaScript on Codecademy. I am finding so many outputs like below when I use while loop.

for (var i=0; i<5; i++){
        console.log("Dhanu identify problems and solve them");
}

var loop = 0;
while(loop<5){
    console.log("Do some more");
    loop++;
}

I am getting an unwanted output in the last line as 4.

enter image description here

Upvotes: 1

Views: 116

Answers (3)

ankit
ankit

Reputation: 125

when you write any statement in developer console then last returned value will be printed...

for example

var a;

it prints undefined on console.

a = 10;

it prints 10 on console.

a = 10; a = a + 5;

it prints 15 on console.

simply when we assign any values or increment or decrement numbers then it returns value after performing that operation...

so, in the above or below code

var loop = 0;
while(loop<5){
    console.log("Do some more");
    loop++;
}

finally loop++ is 4.

Upvotes: 0

Regis Portalez
Regis Portalez

Reputation: 4860

The output you get is simply console.log which logs the last known value of the 'loop' variable: (here in firefox):

enter image description here

It's absolutely not related to your code and you don't have to worry about that.

As stated in another answer, debug console use to log the result of the last line (probably because they are meant to debug).

For example the statement "i = 1" evaluates to "1":

enter image description here

while the statement "var i = 1;" evaluates to "undefined", hence logging "undefined"

you can observe the same behavior by invoking eval on those statements:

enter image description here

Upvotes: 2

grdaneault
grdaneault

Reputation: 840

You're seeing that because the last statement in your while loop is loop++, which "returns" the current value of loop. This is just a side effect of running code in a console like this. Consoles are basically read-execute-print-loops (REPL), and so they need something to print. If you ran this as a script in a webpage you would not see 4

Upvotes: 0

Related Questions