Search code examples
javascripttypestype-conversiontype-coercion

Implicit type coercion with objects


var a = {};
a + 1 // return "[object Object]1"

I know why this happened. Object toPrimitive happened and after a.toString return [object Object] and merge with number But why when I type code like this

{} + 1 // return 1

Object not converted string?

Also why object toPrimitive hint Number return 0 When object convert to number this is look valueOf function and why valueOf return 0?


Solution

  • First one is an object and you're adding object with number

    var a = {};
    a + 1 // return "[object Object]1"
    

    Where as second one is just block statement not object

    {} + 1 // return 1