javascriptnode.jsread-eval-print-loop

What type of function does the Node.JS REPL evaluates even before I hit enter?


I noticed that sometimes in the Node.JS REPL, it evaluates the result of the current expression, even before I hit enter.

But that behavior puzzles me: How does it know if I wanted to evaluate it or not? I know it doesn't hurt to evaluate 4+5, but what if it was a function that involved heavy calculations? Wouldn't it slow down my machine? And even worse, what if the function messed with some internal state, like a global variable?

I tried to google with, with no success. I noticed two interesting things, though: When I try to evaluate Fibonacci recursively, it evaluates until Fib(30), but not Fib(31). My guess is that if the function takes too long to compute, Node.JS gives up on giving us a "preview". But I'm not so sure of how that works internally.

So, how does Node.JS knows exactly if it should evaluate an expression? Is there a name for that "result preview" we see before we hit enter? Is there a way to disable it?


Solution

  • That feature is called eager evaluation and you can learn more about it on this issue.

    When you type an expression, that expression is evaluated with a timeout (to prevent heavy computations) and with the restriction that, if the expression would cause a side-effect, the evaluation is stopped. (code)