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


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


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

        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.

        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!


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;


Dont I have to declare a variable first?


I declared two variables, boolean and i.


I put this:
for (i = 0; i < condition; i++) {
boolean = true;
while(boolean) {
boolean = false;
It is giving a syntax error


The error is:

ReferenceError: condition is not defined


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


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


Add before everything, a value for condition. Examples:

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


Thank you for all of your help, it worked!


@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:


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:


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


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