I cant pass over this Guys! While loop!


#1


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

I don't understand what I have to do? I tried many scenarios but I stuck with infinite loop

ar count=0;

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

loop();


#2

There are a couple of things you can do to get this working:

  1. At the moment, the while loop will never start because the code is saying while(count===3) which means "while the count variable is equal to 3", and since the count starts at 0, it will just skip right over the while loop. So changing count===3 to count < 3 will say "once the count variable is greater than 3, exit the while loop"

  2. In order to not get stuck in an infinite loop, inside the while loop, after the console.log("I'm looping!"); line, you need to make sure that you're adding 1 to the count variable, so every time you go through the while loop you get closer to 3, which means you're avoiding an infinite loop.

Hopefully this helps you out!


#3

Thank you very much but didnt work,
var count=0;

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

loop();


#4

That's almost correct!

The count++ needs to be inside the while loop directly after the console.log("I'm looping!"); line.


#5

It works thanks :slight_smile: even the editor tells me there:slight_smile: is something wrong


#6

one small thing still ... why we have at the end of the code loop();
whats thats means and what we can put insted of it ?


#7

The code below is defining the function, but not actually doing anything yet:

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

And then this code below is what is actually telling JavaScript execute the function:

loop();


So, loop(); isn't anything special in JavaScript, it's just what we chose to name the function. We could change this line

var loop = function(){

to

var myAwesomeLoop = function(){

and then at the bottom of the file, we can call the function by with

myAwesomeLoop();

#8

but here is my question why we called the function again as we wrote all the condition and console.log inside the previous lines!!


#9

The code below doesn't actually do anything

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

If we left our file like that and didn't include loop();, nothing would happen.


#10

take this example

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

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

there is no function and there is no recall ! that confusing me !


#11

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.