Firefox/Chrome: {} + {} etc.

# Axel Rauschmayer (14 years ago)

If I read ES-262 right then I would expect + to do the following if its operands are either {} or []:

  • Convert each operand to a primitive via ToPrimitive()
  • To do so, first try valueOf() (which returns an object which is thus discarded), then toString()

Finally, as at least one operand is a string, perform string concatenation.

Hence not all of the following results in Firefox look OK to me:

[16:33:50.214] [] + []
[16:33:50.217] ""  // OK
--
[16:33:56.098] {} + {}
[16:33:56.099] NaN  // Not OK
--
[16:34:02.455] {} + []
[16:34:02.456] 0  // Not OK
--
[16:35:38.002] [] + {}
[16:35:38.004] "[object Object]"  // OK

Node.js is better:

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

Oddly, Chrome returns the same results as Firefox (different version of V8?)

# Axel Rauschmayer (14 years ago)

Ah! Good call. And, as expected, wrapping the first operand in parens makes the problem go away.

REPL input is tricky to parse correctly in JS, kind of between statements and expressions.

# Luke Hoban (14 years ago)

JS REPLs tend to parse input as Program productions. Parsing "{} + {}" as a block followed by a unary expression is correct according to ES5 grammar for Program. IE behaves the same.

Luke

From: es-discuss-bounces at mozilla.org [mailto:es-discuss-bounces at mozilla.org] On Behalf Of Axel Rauschmayer Sent: Friday, January 27, 2012 8:21 AM To: es-discuss Subject: Re: Firefox/Chrome: {} + {} etc.

Ah! Good call. And, as expected, wrapping the first operand in parens makes the problem go away.

REPL input is tricky to parse correctly in JS, kind of between statements and expressions.

On Jan 27, 2012, at 16:56 , Bradley Meck wrote:

Chrome and FF are treating the leading {} as an empty block statement.

<snip>

# Allen Wirfs-Brock (14 years ago)

On Jan 27, 2012, at 8:38 AM, Luke Hoban wrote:

JS REPLs tend to parse input as Program productions. Parsing "{} + {}" as a block followed by a unary expression is correct according to ES5 grammar for Program. IE behaves the same.

It's not just in Program, it's any statement context. However, it is hard to actually observe outside of a REPL. Try this variant

function f() { {;} + {} }

to more clearly see what is being parsed.

{ } + {}

clearly belongs in anybodies wtfjs list

# Axel Rauschmayer (14 years ago)

JS REPLs tend to parse input as Program productions. Parsing "{} + {}" as a block followed by a unary expression is correct according to ES5 grammar for Program. IE behaves the same.

It's not just in Program, it's any statement context. However, it is hard to actually observe outside of a REPL. Try this variant

function f() { {;} + {} }

to more clearly see what is being parsed.

What works for me is closing my left eye. ;-) www.youtube.com/watch?v=46btEgKmCTo