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


#1

I am having problems with making this code for this lesson, and don't know where to start.


#2

Post the question and your attempt, and I can guide you.


#3
      
        When to 'while' and when to 'for'
      
      
        As we mentioned, for

loops are great for doing the same task over and over when you know
ahead of time how many times you'll have to repeat the loop. On the
other hand, while loops are ideal when you have to loop, but you don't know ahead of time how many times you'll need to loop.

As you saw, however, you can combine a while loop with a counter variable to do the same kind of work a for loop does. In these cases, it's often a matter of preference.

      
    
    
      
        Instructions
      
      
        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!

#4

You need two write one of each loop. Here's a framework for help:

for (i = 0; i < SOMETHING; i++) {
    //Do Something
}
boolean = true;
while(boolean) {
    //Do something
    boolean = false;
}

#5

Dont I have to declare a variable first?


#6

I declared two variables, boolean and i.


#7

I put this:
for (i = 0; i < condition; i++) {
console.log("HI")
}
boolean = true;
while(boolean) {
console.log("NO")
boolean = false;
}
It is giving a syntax error


#8

The error is:

ReferenceError: condition is not defined

#9

You must define condition outside of the loop, or change it to a number.


#10

Can you help me fix it, I cant seem to get it


#11

Add before everything, a value for condition. Examples:

var condition = 5
var condition = 8765
var condition = 2 ** 2
var condition = 12345 / 5

#12

Thank you for all of your help, it worked!


#13

@carson1371 yes the problem is that condition is used here:

for (i = 0; i < condition; i++) {

without being defined. Just to explain the terms. Variable declaration means something like this:

var name;

where you introduce a variable for the first time using var and the name. And variable definition is when you define a type by assigning a value to it:

name = value;

of course you can do this in 1 step:

var name = value;

but just to clear the terms.

So I'm a bit confused about this @cadecodes :

var condition = 5
var condition = 8765
var condition = 2 ** 2
var condition = 12345 / 5

as you only need var for the first and the 3rd seems to be python structure not JS :wink:


#14

Just listing conditions, it's fine if there's var there, but how do you exponentialize in JavaScript? I thought they were the same? :slightly_smiling:


#15

Afaik either x*x or Math.pow(base,exponent) if it gets bigger.


#16

Thanks for showing me, I'll be sure to remember from now on! :slightly_smiling: