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"?
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
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
Going step by step:
{}[0] == undefined
+undefined == NaN
!NaN == true
The conversion is executed this way:
!+{}[0]
( {}[0]
-> undefined
) !+undefined
( +undefined
-> NaN
) !NaN
( NaN
is falsy -> false
) !false
true
Logical not !
always transforms the argument to a boolean primitive type.
Check more about the falsy and logical not .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.