0

Let's consider the following input in terminal

✗ node
Welcome to Node.js v13.1.0.
Type ".help" for more information.

> let a = 13
undefined
> {} + a.toString()
13

> // but
undefined

> let b = {} + a.toString()
undefined
> b
'[object Object]13'

The question is why when you evaluate {} + a.toString() REPL will show a digit 13, but when you assign it to a variable it equals to the expected string '[object Object]13'?

This behaviour happens at least in the V8 (Node and Chrome).

Vlad Miller
  • 2,255
  • 1
  • 20
  • 38

1 Answers1

1

The root problem here is that { ... } in JS is syntactically either a block statement or an object literal expression, depending on the context (wether a statement or an expression is expected). In your second case, it is clearly an expression:

 let b = /*expression context*/

thus {} is an object literal there. In the first case, it is in a statement context, and thus is interpreted as:

  {} // an empty block statement
  + a.toString() // a unary plus operator on "13"
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151