Why doesn't the Node REPL give the same results as the Wat video or my browser console?

For example, in Wat and in the Chrome browser browser:

{} + {} 

have NaN

But in Node REPL it is

 [object Object][object Object] 

The latter, admittedly, makes more sense to me - forcing the rope and then acting is a pretty reasonable thing. However, I donโ€™t understand where this discrepancy comes from, and therefore I donโ€™t understand how much I can trust REPL to understand some simple JS actions.

+3
source share
1 answer

{} is an expression (an empty object literal) and an operator (an empty block).

eval() will try to parse its input as a statement.
If this is not a โ€œnormalโ€ operator (for example, if ), it will be parsed as an expression operator that evaluates the expression.

Therefore, {} + {} parsed as two statements (via ASI): {}; +{} {}; +{} . The first statement is an empty block; the second operator is the unary operator + , which forces the object to a number.
Forcing an object to a number involves calling toString() (which returns "[object Object]" ), and then parsing the result as a number (which is not the case).
eval() then returns this 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 eval as expression with parens. // This catches '{a : 1}' properly. self.eval('(' + evalCmd + ')', 
+4
source

Source: https://habr.com/ru/post/955616/


All Articles