8. When to 'while' and when to 'for'


The code below prints out
"Looped 1 time
Looped 2 time
Looped 3 time

Why is 3 printed out on the very last line?


var count = 1 

while (count < 4) {
    console.log ("Looped " + count + " time");


I changed the code to the following below and it doesn't have 3 as an output on the last line. But I am not too sure why.

var count = 1

var whileLoop = function() {
while (count < 4) {
console.log ("Looped " + count + " time");



Your fist post returns 3 because the while loop is returning your count variable after finishing executing your while code block. This is happening because your codeblock is anonymous. In the function it will only return what you instruct it to with return keyword.

If you were to place count++; before your console.log() than it will only return undefined.


Despite what the while loop name sounds like, you only want to use a while loop while you're going from step A to step Z and you plan that the loop will take you there. A for loop is a controlled while loop. You can control for your initial step, determine the control for when to break the loop, and control the steps increment/decrement.


An example of a while loop would be sorting through an array, or better yet if you understand a relationship between php & mysql, you would use a while loop.

while (query has result) {
echo result;

The above example assumes on a query, you're receive an array of results, and for each echo you move forward through the array, so while there is a next result in array, it will continue to return results.

In my experience with JavaScript you will be using for loops a lot more often, and it may even be safer to use them anyway.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.