When yo while and when to for


#1

When to 'while' and when to 'for'

Why do I get Syntax error? I cant understand why. Code below:

bool = true

while( bool ) {
    console.log("While looping")
    bool = false
}

For ( var i = 0; i < 3; i++ ) {
    console.log(i)
}

Grateful for any help!


#2

you for loop, for is a keyword, an keywords are case-sensitive. Make for all lowercase (your first letter is uppercase)


#3

At first i m telling you
write for not For
For( var i = 0; i < 3; i++ )//wrong
for( var i = 0; i < 3; i++ )//right

now i telling when for loop and when while loop
We are learning how to program because we don't want to do boring, repetitive work! The computer should do that.

This first exercise is a good example of exactly why you want to learn for loop

console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);

Do want to write same things again and again
so use for loop for that

for(var i = 1; i < 6; i++) {
console.log(i);

instead of manually typing in console.log five times, we can use a for loop to do.

for loop syntax

for ([initialExpression]; [condition]; [incrementExpression])
statement

Great work with for loop!
But what if you didn't know ahead of time when to stop looping?
then use while loop
run this code:

var coinFace = Math.floor(Math.random() * 2);
console.log(coinFace)

while(coinFace === 0){
console.log("Heads! Flipping again...");
var coinFace = Math.floor(Math.random() * 2);
}
console.log("Tails! Done flipping.");

any question?

@wildwuzzy


#4

ah! Great thanks guys.