rajakvk
rajakvk

Reputation: 10123

Why does `+ ! {} [true]` evaluate to 1?

In JavaScript the following line of code gives answer as 1

+ ! {} [true]

I couldn't understand how?

Any gurus explanation is appreciated.

Upvotes: 7

Views: 132

Answers (2)

rab
rab

Reputation: 4144

I tried to explain it through code .

var emptyObject = {};
    valueOfUndefinedKey = emptyObject['key_not_exists'],
    itsNot = !valueOfUndefinedKey ,
    finalConvertedNumber = +itsNot ;

console.log(
    emptyObject,
    valueOfUndefinedKey,
    itsNot,
    finalConvertedNumber
) 

which prints

Object {}

undefined

true

1

Upvotes: 3

Romain Braun
Romain Braun

Reputation: 3684

{} is an empty object.

So {}[0] or {}[true] or {}[1] etc.. are undefined

adding ! casts {}[0] as a boolean, returning the opposite. (undefined becoming false, it therefore returns true).

adding + casts it as an int, so true becomes 1.

Upvotes: 5

Related Questions