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?
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?
Share Improve this question asked Aug 23, 2015 at 20:03 Andy LiAndy Li 3272 gold badges3 silver badges7 bronze badges 5 |3 Answers
Reset to default 11return
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.
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.
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/
return
statement needs to be inside a function. What are you trying to do anyway? – Sebastian Simon Commented Aug 23, 2015 at 20:04return
statement directly inside awhile
loop will result in only one iteration being executed. (It makes your loop useless). However, if you replace this line with something likeconsole.log(i);
, it should print 0, 1, ..., 99 to the console. – blex Commented Aug 23, 2015 at 20:07return "the number is " + i
withconsole.log("the number is " + i)
, press F12, choose the "console" tab, press F5 (assuming that your code is embedded into a web page). – user1636522 Commented Aug 23, 2015 at 20:22