Why function?


#1

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

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

loop();

what is the need for function here? what if it is not there, would it not work?
if not, why is that?
is it there because I am adding count++ in my while loop?

I just learned while loop, but I thought as long as it is true and eventually result in false it will loop and do what I tell it to do. so I don't see why it has to be inside of a function to work this time.


#2

The function is there so that you can loop multiple times by calling loop().
If it wasn't there, you would need to type the code more times.


#3

As @jibblyj already said the purpose of a function is basically that the code in it is reusable, so you can loop again with another loop() instead of having to write the whole code again. But as you're calling it only once it should in principle to the same thing without the function.

Also when using a function be careful what is inside and what is inside of it. As you've learned in the track about functions there are global and local variables. As count is declared outside and not redeclared inside it is global. So by running the function and running the loop in the progress you update count so after the loop it will be 3 as that was the stopping condition. So when you run the function again the loop won't work as it is already 3. So better move this statement inside of the function but before the loop:

var count = 0