5

In JavaScript the following line of code gives answer as 1

+ ! {} [true]

I couldn't understand how?

Any gurus explanation is appreciated.

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
rajakvk
  • 9,775
  • 17
  • 46
  • 49

2 Answers2

4

{} 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.

Romain Braun
  • 3,624
  • 4
  • 23
  • 46
2

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
rab
  • 4,134
  • 1
  • 29
  • 42