8
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?

5
  • 2
    Is this all of your JS code? The return statement needs to be inside a function. What are you trying to do anyway? Commented Aug 23, 2015 at 20:04
  • 3
    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.log(i);, it should print 0, 1, ..., 99 to the console. Commented Aug 23, 2015 at 20:07
  • @blex And if you put the return statement before the end of the loop, it will result in less than one iteration being executed. Making it even more useless. Commented Aug 23, 2015 at 20:20
  • Replace return "the number is " + i with console.log("the number is " + i), press F12, choose the "console" tab, press F5 (assuming that your code is embedded into a web page). Commented Aug 23, 2015 at 20:22
  • Thanks, I will use console.log() Commented Aug 23, 2015 at 20:25

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.