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.
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.
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.
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.
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.
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.
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++); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With