1

I have a difficulty of understanding why alert shows me a strange things in the following expression.

alert(!+{}[0]); //it shows "true"

Why "true" but not "undefined"?

Alexey
  • 79
  • 3

4 Answers4

2

Why "true" but not "undefined"?

Because ! is a boolean operator which always returns a boolean value. It would never produce the value undefined.

!false     // true
!''        // true
!null      // true
!undefined // true
!NaN       // true
!0         // true

Related: What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

This is because the NOT operator ! will always return a boolean value, so if you were to examine your statements, you could break them down as follows :

{}[0]        // yields undefined
+(undefined) // assumes arithemetic, but doesn't know how to handle it so NaN
!(NaN)       // Since a boolean must be returned and something is there, return true
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
0

Going step by step:

{}[0] == undefined
+undefined == NaN
!NaN == true
Gokhan Kurt
  • 8,239
  • 1
  • 27
  • 51
0

The conversion is executed this way:

  1. !+{}[0] ({}[0] -> undefined)
  2. !+undefined ( +undefined -> NaN )
  3. !NaN (NaN is falsy -> false)
  4. !false
  5. true

Logical not ! always transforms the argument to a boolean primitive type.
Check more about the falsy and logical not.

Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41