Node: {} + [] REPL bug?

Created on 8 Jun 2020  Â·  10Comments  Â·  Source: nodejs/node

In the REPL, on 12+ version, I am seeing the below.

> {} + []
'[object Object]'

^ This should be 0

image

  • Version: 12+
  • Platform: 18.7.0 Darwin
repl

Most helpful comment

REPL is an expression context, the input is actually ({} + []).

All 10 comments

This also manifests when you do console.log({} + []) which prints '[object Object]' instead of 0, in many many node versions.

The direct repl behavior seems limited to 12+.

I've been informed that in fact this is correct; {} + [] in a statement context is "a block" and then +[], which is 0, but in an expression context (or as ({}) + [] is '[object Object]'.

Also:

> [{}+{}, {}+[]]
[ '[object Object][object Object]', '[object Object]' ]

This is not a bug. String({}) is '[object Object]' and String([]) is ''.

Nods, [{} + []] will be '[object Object]' but {} + [] in REPL should be 0?

REPL is an expression context, the input is actually ({} + []).

We handle REPL input as expression context as @devsnek pointed out. See https://github.com/nodejs/node/blob/651088c3e6b6399a3e656e397c3845b970ad7903/lib/repl.js#L355-L358
This also applies to e.g., { b: 1 }.b.

As @ljharb highlighted, on node <v12 {} + [] evaluates to 0 on the REPL [devtools might a different story]

As @devsnek and @BridgeAR pointed out, this is not a bug, but intentional – the REPL prefers to evaluate as expressions before evaluating as statements. So the current one is the expected behavior, and the pre-v12.x one is considered the buggy one.

I’ll close this as I don’t think there’s anything we can do here.

hmm - i don't see this REPL change listed in the blog post: https://nodejs.org/en/blog/release/v12.0.0/

Clearly it's the right fix to make, and I assume its omission is an oversight - could someone link me to the PR that changed it?

Was this page helpful?
0 / 5 - 0 ratings