Javascript while loop return value

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:

  1. Let blockValue be the result of evaluating StatementList.
  2. Set the running execution context’s LexicalEnvironment to oldEnv.
  3. 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.

Leave a Comment