Hacker News new | ask | show | jobs
by nodesocket 5253 days ago
Interestingly the results from jsc, are different from node.js:

----- jsc ------

   [] + []
   
   > [] + {}
   [object Object]
   > {} + []
   0
   > {} + {}
   NaN
------ node.js ------

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

This appears to be a peculiarity of the REPL implementations, not a difference between V8 and JSC. d8 (and the Chrome console) behaves the same way as jsc, while you can make d8 and jsc behave the same as the node REPL by wrapping each statement in parentheses:

  d8> ([] + [])
  
  d8> ([] + {})
  [object Object]
  d8> ({} + [])
  [object Object]
  d8> ({} + {})
  [object Object][object Object]
So I believe this is merely erroneous behavior of the console, not a weirdness of JavaScript itself.
No, it's more subtle than that. By wrapping in parenthesis, you're making it an expression. When you just say "{}+[]" in e.g. Chrome, the first {} is parsed as a block. So what you see printed is the result of "+[]", which is 0. This is why {}+[] is not equal to {}+[] without parens. This may also be why Node gives different results; I'm not sure.

I didn't mention any of this in the talk (it would've killed the flow ;). Instead, I glossed over it and interpreted the syntax as any sane programmer would.

I understand why it happens. I'm saying that what you're pointing out is not in the nature of JavaScript, it's in the REPL. It's just wrong; there is no other situation where that code would evaluate that way. node is behaving "properly", showing you what value you can expect if you, say, assign that expression to a variable.

I guess it's an amusing bit of sleight-of-hand, but using it to mock JavaScript seems, I don't know, tasteless. Doesn't it have enough problems without inventing more?

It's a joke. Relax.
Yes, I saw the joke.

To clarify, I thought the first part of the talk was funny. Here's a weird bit of Ruby. Hah! Here's a weird bit of JavaScript. Hah! Here's some JavaScript to make you think it's weird in a way it actually isn't! Uh, okay? Just don't see what's funny about that, I guess.

I don't even understand what the last node.js entry is. Is that an array with two objects?

Also, I'm on an old version of node, but my output matches jsc.

The other reply is right, to clarify String({}) === "[object Object]"

I think the actual video was a little misleading, [] + {} == the string "[object Object]" not an object. The square brackets are just part of the tostring method and are unrelated to the square brackets of arrays.

The `toString` of two Object-s concatenated, I think.