-2

Before performing an operation on operands, all operands must be converted to primitive type, I understand that how toPrimitive() works in javascript

Here 1+{} gives "1[object Object]" which I expects

But in case of {}+1 I expect [object Object]1" but it gives 1

What I am missing?

manjeet
  • 1,497
  • 10
  • 15
  • Javascript's type system is... quirky. These situations rarely are relevant in real-world coding, but one decent rundown of what's going on is https://medium.com/dailyjs/the-why-behind-the-wat-an-explanation-of-javascripts-weird-type-system-83b92879a8db – Daniel Beck Aug 09 '18 at 16:17
  • 2
    `{} + 1` is the same as `+1` because `{}` at the beginning of a line (in statement context rather than expression context) is a block. There is no object in that line, so it has nothing to do with types, just syntax ambiguity. – Sebastian Simon Aug 09 '18 at 16:17
  • 1
    Good question. I think no one knows, that's why you get downvoted. Javascript is Javascript... https://martin-thoma.com/javascript-wtf/ https://www.destroyallsoftware.com/talks/wat – Joel Aug 09 '18 at 16:17
  • It's like how `[] != "\t"` and `"\t" != "0"` and `"0" != []` but all of those things are `== 0`. JavaScript is quirky. If you want specifics you're going to have to read the [ECMAscript](https://en.wikipedia.org/wiki/ECMAScript) standard. – tadman Aug 09 '18 at 16:17
  • (waw some people do actually know, I'm impressed) – Joel Aug 09 '18 at 16:20
  • 5
    @Joel No, it gets downvoted, because this has been asked several times before. – Sebastian Simon Aug 09 '18 at 16:20
  • Personally, I'd expect `NaN` to be the answer in both scenarios yet here we are in 2018 and JS still doing quirky stuff like this ¯\_(ツ)_/¯ – James Aug 09 '18 at 16:22
  • 2
    @James: Changing this kind of behavior would break existing code, so it can never change. – SLaks Aug 09 '18 at 16:23
  • @SLaks totally get that but one could make a case for if fixing this behaviour broke existing code then said code probably isn't correct anyway. I would imagine if code like this was run under a static type checker it would flag. – James Aug 09 '18 at 16:30
  • @xufox imagine you are quite new to js. Would you know the `'Wat' talk for CodeMesh 2012` ? (Yes this is a good dupe, but this is still a good question so IMO no reason to downvote) – Jonas Wilms Aug 09 '18 at 17:17
  • @JonasWilms agree, good point, the question title is more likely to be found over the other question. Although, doubt votes will affect someone's ability to find this page and you'd expect organically overtime if people found it helpful enough they'd vote the question up (even if it is a dupe). – James Aug 09 '18 at 20:54

1 Answers1

0

I think its because {} is treated as a block instead of object to add 1. e.g

{}+1 = 1
({});+1 = 1
({})+1 = "[object Object]1"
a = {}+1 // a is "[object Object]1"
Rainer Plumer
  • 3,693
  • 2
  • 24
  • 42