Why Does Node Repl Not Give The Same Results As Wat Video Or My Browser Console?
For example, in both Wat and in my Chrome browser: {} + {} is NaN But in Node REPL, it's [object Object][object Object] The latter admittedly makes more sense to me - coercing to
Solution 1:
{}
is both an expression (an empty object literal) and a statement (an empty block).
eval()
will try to parse its input as a statement.
If it isn't a "normal" statement (eg, an if
), it will be parsed as an expression statement, which evaluates an expression.
Therefore, {} + {}
is parsed as two statements (via ASI): {}; +{}
. The first statement is an empty block; the second statement is the unary+
operator which coerces an object to a number.
Coercing an object to a number involves calling toString()
(which returns "[object Object]"
), then parsing the result as a number (which it isn't).
eval()
then returns that as the value of the final statement.
Node wraps its REPL input in ()
to force it to be parsed as an expression:
// First we attempt to evalas expression with parens.
// This catches '{a : 1}' properly.
self.eval('(' + evalCmd + ')',
Post a Comment for "Why Does Node Repl Not Give The Same Results As Wat Video Or My Browser Console?"