Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript, while loop return

var i = 0;
while(i < 100){
   return "The number is " + i;
   i++;
}

What is wrong with my return statement? Why can I return a string plus a variable?

like image 515
Andy Li Avatar asked Aug 23 '15 20:08

Andy Li


People also ask

Can you return from a while loop JavaScript?

Having a return statement directly inside a while loop will result in only one iteration being executed. (It makes your loop useless). However, if you replace this line with something like console.

Can you return from a while loop?

It is good practice to always have a return statement after the for/while loop in case the return statement inside the for/while loop is never executed. Otherwise, a compile-time error will occur because the method cannot return nothing (unless it has the Java reserved word "void" in the method header).

How do you exit a while loop in JavaScript?

The break statement breaks out of a switch or a loop. In a switch, it breaks out of the switch block. This stops the execution of more code inside the switch. In in a loop, it breaks out of the loop and continues executing the code after the loop (if any).

How does a while loop work in JavaScript?

The while statement creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.


1 Answers

return means end of function and return some value. Any statements after return statement will not be executed and the execution of a function will terminate at return statement. So, return in your case will make the loop to execute only one and terminate it.

like image 174
Sailesh Babu Doppalapudi Avatar answered Oct 22 '22 05:10

Sailesh Babu Doppalapudi