Why is this while loop not effective?


#1

I was trying to design a while loop which would run three times. I was wondering why this code wouldn't work:

var count = 0

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

loop(count);

#2

If you call a function that exits itself and then loops three times, then it didn't loop at all because it isn't running any more, it has exited.


#3

can you explain more?
and why would this not work:
var count = 0

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

}

};

loop(count);


#4

Okay so I just did the same code and it worked when I didn't use the return keyword. Why is that?
I'm probably misunderstanding how to use 'return' - when do I use it?


#5

The "return" keyword is used when you have a certain value that you need as an output from the function. Since in this example there is no value that needs to be output to the rest of the program, the "return" is obsolete, cause the function itself does what it's intended to do, in this case it prints out "I'm looping!" a certain amount of times.

Also, within the while function in the first example you haven't included a parameter which will make the loop dynamic, precisely which will increase your counter by 1 in each loop. In the second code you've made that change, but you still have the "return" keyword which is obsolete. The proper code, within the function, should look like this:

var loop = function(number){
while(number<3){

console.log ("I'm looping!")
number++;

}

I would also advise a more flexible approach to this kind of function in which you can decide how many loops you would like to make, but this kind of program also easily done with a for loop. Here's my example:

var count = prompt("How many loops would you like to see?");

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

loop(count);


#6

Thanks, that helped a lot!


#7

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