While loop works but why?


#1

Practice Makes Perfect

So, my code doesn't behave incorrectly, I just want to know why it works the way it does. After several attempts at writing the code how I thought it would work based on my understanding, I ended up just copying code from this forum (just to see it work).

Why do you have to leave the function without a parameter? Why does "count++" go after the action?

Sorry, this section is just SUPER confusing for me...


r count = 0

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

loop();


#2

Because you don't need to feed a parameter to the function since it takes no input. I'm also guessing that you wrote var count = 0 and it just didn't copy. What you're saying is WHILE the count variable is less than 3, do THIS. After you do that, you need to increase the count variable by 1 so it will eventually be more than 3 and the loop with stop. If you don't the loop will continue forever, and you will crash your browser.

//set the initial count variable
var count = 0

//creating a function that doesn't need to be fed an input
var loop = function(){
//starting a while loop that will do something WHILE count is less than 3
	while(count < 3){
//telling the loop what it should do each time it runs
	    console.log("I'm looping!");
//telling the count variable to increase by 1 every time the loop runs
	    count++;	
	}
}

//function that runs a loop to print "I'm looping!" 3 times.

#3

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