Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript While loop repeats last number when counting from 1 to 5 when run on console [duplicate]

When running following code on console:

var counter=0; while(counter<5){ console.log(counter); counter++; }

console o\p: 0 1 2 3 4 4

whereas for following code works fine, without repeating last value:

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

console o\p: 0 1 2 3 4

Now, if I place above for loop after above mentioned while loop , output is perfectly fine:

var counter=0; while(counter<5){ console.log(counter); counter++; } for(var i=0; i<5; i++){ console.log(i); }

console o\p: 0 1 2 3 4 0 1 2 3 4

whereas, if I place while loop after for loop , repetition of last number found.

for(var i=0; i<5; i++){ console.log(i); } var counter=0;while(counter<5){ console.log(counter); counter++; }

console o\p: 0 1 2 3 4 0 1 2 3 4 4

Request all to provide a reason on this unexpected behavior of while loop. Thanks.

like image 933
Sarge Avatar asked Jul 15 '15 15:07

Sarge


People also ask

How do you count the number of times a loop is executed in Javascript?

number ) { //run the loop while a number from the list + the value is less than or equal to the number the user entered while(coins[i] + value <= number){ value += coins[i]; console. log(coins[i]); //count how many times the loop runs.

How does a while loop work in Javascript?

The while loop starts by evaluating condition . If condition evaluates to true , the code in the code block gets executed. If condition evaluates to false , the code in the code block is not executed and the loop ends.

Do while loop in Javascript execute?

The do... while statement creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.

How do you end a while loop in Javascript?

You use the break statement to terminate a loop early such as the while loop or the for loop. If there are nested loops, the break statement will terminate the innermost loop. You can also use the break statement to terminate a switch statement or a labeled statement.


2 Answers

When performing operations in the console, the return value of the last executed line is always output.

That means that simply writing

var counter = 0; ++counter;

will log 1 to the console.

The same is happening in your loop, the return value of the last counter++ is output to the console as the value of the last executed expression.

like image 76
Etheryte Avatar answered Nov 15 '22 13:11

Etheryte


The output of the log method depends on the javascript engine of the browser. The last value printed is not output of the loop itself.

Try: var counter=0; while(counter<5){ console.log(counter++); }

like image 43
Dipen Shah Avatar answered Nov 15 '22 13:11

Dipen Shah