2

I have a question about type conversion in JS

{} + 4 // 4
4 + {} // '4[object Object]'

But

4 + new Object() // '4[object Object]'
new Object() + 4 // '[object Object]4'

The language spec says that {} and new Object() declarations are the same, so why does the JS engine behaves this way?

veralex
  • 21
  • 4
  • `The language spec says that {} and new Object() declarations are the same` Yes. But the key is them being *declarations*. In the case of `{} + 4` that's not a declaration. It gets resolved as an empty code block (no-op), followed by a unary `+`, followed by a `4`. If you wrap this in brackets `({} + 4)`, you'd get a consistent result, since it's now a declaration of an object literal. – VLAZ Sep 21 '18 at 11:12
  • @Quentin - i think the [JavaScript type conversion: (true && 1) vs (true | | 1)](https://stackoverflow.com/questions/8559920/javascript-type-conversion-true-1-vs-true-1) which is listed dupe is not relevant to this question, since it doesn't deal with logical operators. – VLAZ Sep 21 '18 at 11:15
  • @vlaz — It isn't. That dupe has nothing to do with me. It was a later edit. – Quentin Sep 21 '18 at 12:08
  • @Quentin apologies, then. I didn't see anybody else's name and I don't know how to check moderation actions (or if I'm able). Thanks for acting to remove it. – VLAZ Sep 21 '18 at 12:11

0 Answers0