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


#1

Hello, I am on my first 5 days of Javascript and just brain dead. Besides help with this code, can you give me some encouragement?

"Write two loops in the editor: one while, one for. No restrictions on this one; just make sure your loops are syntactically correct, and be careful to avoid infinite loops!"

https://www.codecademy.com/en/courses/javascript-beginner-en-ASGIv/2/1?curriculum_id=506324b3a7dffd00020bf661#

var count = true
while(count){
    console.log("Hello!")
    var count = false;}
}
    
for(var i=1; i<11; count++){
    console.log(i);}
    return(
}

#2

Don't give up! You can do it!

Remove the closing brace there.

and there.

do something with this.

And don't give up! :stuck_out_tongue:


#3

OK, I am brain dead on:

return(  \\ print numbers 1-10

var count = true
while(count){
    console.log("Hello!")
    var count = false;
}
    
for(var i=1; i<11; count++){
    console.log(i);
    return( \\ ??
}

#4

What's this for? I don't think you need this here, do you?
You need to print those numbers here;

for(var i=1; i<11; count++){
    console.log(i);
    return( \\ ?? // console.log() the value of the variable named i.
}

#5

return may only be used in a function. That line should be removed.

Aside:

It's tempting to write,

return(something);

but return is not a function, and we don't use parens unless we are grouping.


#6

And somehow magically this worked!! Was this challenging for you all in the beginning?

var count = true
while(count){
console.log("Hello!")
var count = false;
}

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

Hello!
1
2
3
4
5
6
7
8
9
10


#7

There is lots to learn at first, but gradually you will get comfortable if you practice, lots.

A variable is only declared once in the session, and not again. Inside a loop is not a good place to declare a variable, either.

var flag = true
while (flag) {
    // code
    flag = false;
}

JavaScript permits us to declare a variable without defining (giving a value) it.

var something;

The above declares the variable.

something = "some value"

The above defines the variable.