I have a simple question regarding while loop in Javascript. When I run this simple loop in browser console:
var count = 0;
while (count < 10) {
console.log(count);
count++;
}
The output to console log is 0,1,2...9. (as expected). However there is one more number which is returned to the console:
<- 9
Where does this return value come from?
I assume this is the return value of count++ expression
. But why is the value not returned by every single loop?
Is it possible to somehow catch that returned value to a variable?
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.
The reason is because the while loop has an exit point controlled by a boolean variable. It doesn't need a return statement, which is only to be used in a body of a function.
Yes, function's always end when ever there control flow meets a return statement. The following example demonstrates how return statements end a function's execution.
return statement not only breaks out of the loop but also the entire function definition and shifts the control to the statements after the calling function. If you want to break out of the loop then use break. Use return only when it's necessary to exit the function definition.
Read-eval-print-loops (REPLs) like browser consoles show the last result that the code generated. Somewhat surprisingly, JavaScript while
loops and blocks have a result. For blocks, it's the result of the last statement in the block. For while
statements, it's the result of the last iteration of the statement attached to the while
(a block in your case).
Here's a simpler example with just a block:
{1 + 1; 3 + 3;}
In a REPL like the browser console, the above will show you 6, because it's a block containing two ExpressionStatements. The result of the first ExpressionStatement is 2 (that result is thrown away), and the result of the second one is 6, so the result of the block is 6. This is covered in the specification:
- Let blockValue be the result of evaluating StatementList.
- Set the running execution context’s LexicalEnvironment to oldEnv.
- Return blockValue.
while
loop results are covered here.
Is it possible to somehow catch that returned value to a variable?
No, these results are not accessible in the code. E.g., you can't do var x = while (count < 10 { count++; });
or similar. You'd have to capture the result you want inside the loop/block/etc., assigning it to a variable or similar. Or (and I'm not suggesting this), use eval
as Alin points out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With