Introduction to 'While' Loops in JS Q&A


#1

Hello everyone,
I am having a lovely time coding until...the wicked witch of the west appears and turns me into a frog (me = :frog:)
I am obviously kidding (or was that not obvious enough? I will change it if it isn't :eyes:) so I need some help to solve my problem,
I am on lesson 5/11 or 'Practice makes perfect' (I totally agree) and I'm following the hint but I am stuck at the point "...then do count++ each time we console.log() inside the loop, we'll be able to track how many loops we've made..." Here's my code:

//Remember to set your condition outside the loop!
var count =0;

var loop = function(){
    while(){
        //Your code goes here!
    }
};

loop();

I'd highly appreciate some help
Thanks


#2

@camillita,

What they are trying to achieve,
that you are able to use a while-loop.

             point of entry
             in while-loop
                   |
                   V
 ->  while ( condition===true )   -->EXIT--->if condition===false
|       {  // begin of while-code-block  
^
|          // your code that will be executed 
|          //       as long as while-condition === true
|
^<- - - } //end of while-code-block, 
                     while-condition is checked again !!

They give you the code:

var understand = true;

while(understand){
	console.log("I'm learning while loops!");
	//Change the value of 'understand' here!
	understand=false;   //<<== you make sure
                               while-condition===false
}

1 You assign true to the variable understand

2 The while-statement -tests the condition-,
--which is the variable understand with its value being true
3 Access is granted to the while-code-block
4 console.log("I'm learning while loops!"); is executed.
5 assignment of the false value to the variable understand
6 END of while-code-block is reached,
goto 2 //The while-statement -tests the condition-, understand

As understand renders to false,
the while will NOT execute its body,
and will EXIT.

Reference::

google search
== the Book ==
javascript while site:developer.mozilla.org
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while

== discussions / opinions ==
javascript while vs do while site:stackoverflow.com
= http://stackoverflow.com/questions/5599027/the-do-while-statement

== guidance ==
www.crockford.com
http://javascript.crockford.com/code.html
http://javascript.crockford.com/survey.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript


#3

Well the idea of a while loop is pretty simple:

check condition -> if true run the code -> check condition -> run code -> if false -> exit loop.

So if you code in inside the {} of the while loop contains a statement that increases the value of a variable by 1 then you could build a counter for how many times the loop run. And if you make your condition depended of this counter you can specify how many times a loop should run e.g.

var i = 0;
while (i <6){
   do something
   i=i+1 // or i++ what does the same
}

#4

Thanks a lot guys (@haxor789 & @leonhard_wettengmx_n) for the great explanations. So all I have to do is to write a true condition, like 3 * 6 === 18 in the () after the while or does the editor want a special one?
As for the console.log()I'm not so sure what to put. Any suggestions?
So far my code looks like this if what I said was true:

//Remember to set your condition outside the loop!
    var count =0;

    var loop = function(){
        while( 3 * 6 === 36 ){
            //Your code goes here!
        }
    };

    loop();

I don't want to run the thing because (1) it probably won't run since its not really doing anything (2) I recently crashed my browser and I don't want that to happen again.
Thanks


#5

Well the problem with an absolutely true condition like3 * 6 === 36 or simply true is that this will always stay true and you have no way to change it. Meaning it runs and runs and runs until your browser refuses to handle it. So better use a condition that is based on a variable like for example:

counter < 15

then you start with a value of counter for which this condition is true e.g. 0 and inside of the loop you change the value of counter with every loop e.g. add 1 to it by counter = counter +1 or simply counter++. So what happens this way is that after here 15 loops the value of counter will be 16 therefore > 15 and so as the condition is false you finished the loop and go on with the code.

For the console.log mostly the message is mentioned either in the instruction or it doesn't matter at all just pick one that you like to read :smile:


#6

Like this?

//Remember to set your condition outside the loop!


var loop = function(){
    while(counter > 3){
        //Your code goes here!
    counter++
    console.log("Is this loop gonna work?")
    }
};

loop();

What's the loop there for? I think I actually forgot what the thing was asking me to do!
???
:smile:
I don't want to run it without an approval.


#7

With loop you mean the function named loop, right?
I guess it is about a review on functions and about making the code reusable. It is not directly related to the exercise and as far as I know you could even delete it but you could as well use it and just write the code you want to see inside of it's curly braces.

On the while loop. Close but it still has some flaws. First of all counter needs declaration and an initial value otherwise counter would be literally undefined and undefined > 3 would be false. Therefore the loop would not run even once and there wouldn't be much point in it. So Maybe start with var counter = 5; before the while loop inside of the loop function. And the other thing is that you need to consider the direction in which you change your values. Here you say counter is bigger than 3 so you need to start with a value bigger than 3 to make the loop run. So far so good but if you then use counter++ inside of the loop you make it even bigger:

var counter = 5
5 > 3 ? Yes run loop 
...
counter ++ -> counter =6
6> 3? Yes run loop
...
counter ++ -> counter = 7
...

as you can see this will never stop so if you have a condition > a number you're more likely to decrease the value by e.g. counter--. Hope this make sense.


#8

Grrrreat. Don't worry ,I understood...I think :wink: o should it be like this?

//Remember to set your condition outside the loop!
var count = 5 ;

var loop = function(){
    while( count > 3 ){
        //Your code goes here!
    count++  
    }
};

loop();

Oh, I'll delete the loop() too.

...so...

Thanks


#9

Well if you delete he loop() then nothing will happen (nothing bad but also nothing at all) because that is the start signal to run the code in your function :smile:

For the loop maybe my pseudo code example wasn't clear enough. A while loop is just a repeating if, you have a condition and if it is true you run the code if in {} and if it is not you skip it. The difference is that if you successfully execute the {} part you mysteriously jump back to before the while loop and do the same thing again. Maybe have a look at this:
http://www.pythontutor.com/javascript.html#togetherjs=zF4cln7qKn
As said what you keep in mind is that you should start your condition to be true and change the variable in a way that it becomes false based on an event or based on a certain amount of loops. Here you want to specify a certain amount of loops. So what you do is to start of with a true condition such as 5 > 3 and then decrease 5 by count-- until it is 3 then the condition is false and you quit the loop. If you increase it the condition will stay true forever and you crash your browser. btw crashing your browser is a bit hard afaik it doesn't do real damage because most modern browsers hint you that there is something wrong still it's better not to have unintended infinite loops. Just because they prevent your code from working correctly. Does this make more sense?


#10

I reread your pseudo code and I realized that I just wasn't thinking properly, it was perfectly clear :stuck_out_tongue_closed_eyes:
What should I put in the loop? Like...console.log("GO, start the loop") :innocent:
Is this "better"?

//Remember to set your condition outside the loop!
var count = 5 ;

var loop = function(){
    while( count < 3 ){
        //Your code goes here!
        count--
    }
};

loop();

I believe that since I have been stuck on this thing for forever that I have started to forget how to write javascript
Thanks


#11

That's much better!:smile: You should at least be able to run this without getting your browser to crash. One last thing as the function makes your code reusable it would make sense to move the var count = 5 into the function:

var loop = function(){
//Remember to set your condition outside the loop!
var count = 5 ;
    while( count < 3 ){
        //Your code goes here!
        count--
    }
};

loop();

run your code as is twice meaning add another loop(); to the end of it and then run the one in this post and observe the difference and you should get why :wink:
Good Luck and Merry Christmas :christmas_tree:


#12

You. Are. Awesome.!.
Thank you sooooooooooooooooooo much.
and Have a Very Merry Christmas :christmas_tree: :gift:


#13

I was having trouble with this too, and when I figured it out I wanted to punch myself in the face! The hint helped me on this one. I followed the steps in the order given: If we create a variable called count and set it to 0 outside the loop (on line 2), then do count++ each time we console.log() inside the loop, we'll be able to track how many loops we've made. If we set the while condition to be count < 3, that should do the trick!
I hope this helps!
var count = 0

var loop = function(){
while(count < 3){
count++
console.log("I'm looping!")
}
};

loop();


#14

One further hint: think about moving the var count = 0 inside of the function before the while loop. If you wonder why, run your function twice:

loop();
loop();

before and after to see the reason.


#15

Thank you, haxor789!


#16

Hey folks: I'm back again :stuck_out_tongue_winking_eye:
I'm on the next lesson and when I pressed save n' submit code I got unresponsive script and so I want someone to check my code. Here it is!

for(i = 3; i < 33; i++) {
    console.log(i);
}

var count = 3; 

while(count > 2) {
console.log(count);
count++;
}

Thanks!


#17

this is an infinite loop count is already > 2 if it is 3 and as you keep increasing it, it will always stay > 2 which keeps the loop infinitely running.


#18

Thanks a lot @haxor789! :smile: