Andy Li
Andy Li

Reputation: 327

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?

Upvotes: 8

Views: 33169

Answers (3)

reidm
reidm

Reputation: 19

I'm not exactly sure what you want to do with this text, but return will take you out of the function. If you want to display this text, you could use <div id="demo"> and then use the function to create text inside of it like this:

var i = 0;
while(i < 100){
    document.getElementById("demo").innerHTML += "<p>The number is " + i + "</p>";
    i++;
}

http://jsfiddle.net/rmerzbacher/fdu7aauz/

Upvotes: 0

Sailesh Babu Doppalapudi
Sailesh Babu Doppalapudi

Reputation: 1546

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.

Upvotes: 12

Srinivasulu Rao
Srinivasulu Rao

Reputation: 309

First of all your code should be inside a function. Secondly the return statement which u have written inside the for loop will execute the result only once and it will come out of the entire function.

Upvotes: 0

Related Questions