When to do 'while' and when to do 'for'


#1

Hello. So my code for this step works fine, but I'm still not grasping the concept entirely. Can someone show me how I would change my 'while' loop to print out the same output as my 'for' loop?

Here is my code:

// for loop
for (var counter = 1; counter < 6; counter++) {
	console.log("I am", counter, "years old");
}

// while loop
var age = 0
var loop=function(){
    while(age){
        console.log("I am", age, "years old");
        counter++
    };
};
loop();

My 'for' loop prints the following:
I am 1 years old
I am 2 years old
I am 3 years old
I am 4 years old
I am 5 years old

'while' loop is not printing anything at the moment.


#2

@kimbergee,

-1

A little bit of Documentation
the for-loop:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for

the while-loop:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while

the do-while-loop:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while

-2

With using the age variable as condition in your =while= loop
you are running into one of the Javascript specifics.

0 ( zero ) is interpreted as a so-called falsy,
and therefore your =while= loop codeblock was NOT run.....
https://developer.mozilla.org/en-US/docs/Glossary/Truthy
https://developer.mozilla.org/en-US/docs/Glossary/Falsy
http://www.codecademy.com/forum_questions/538d5bf9548c3534250012a1

-3

Take care that you use a =static= condition in your =while= loop condition
as your =while= loop will become an infinite loop !!!!
You could use age < 6 as condition
and within the =while= codeblock increment your age using age++


#3

Thanks @leonhard_wettengmx_n! Figured it out.

// for loop
for (var counter = 1; counter < 6; counter++) {
	console.log("I am", counter, "years old");
}

// while loop
var age = 1
var loop=function(){
    while(age < 6){
        console.log("I am", age, "years old");
        age++
    };
};
loop();