May 15, 2018 β’ βοΈ 2 min read
When I was coding, there was a situation that if an array has values, it will return true. So I wrote like this
bool = !!array
. But, unexpectedly whenarray = []
,bool
isfalse
, nottrue
.
string
or empty Array
is conversed to Boolean
, it must return false
.// Conversion
> Boolean("")
false
> Boolean([])
true
// Implied Conversion
> !!""
false
> !![]
true
''
is false
, []
is true
.// Loose Equality
> "" == false
true
> [] == false
true
''
is false
(of course), []
is false
too.[]
is Object
, and false
is Boolean
. So in the table, it is applied that ToPrimitive([]) == ToNumber(false)
and recursively ToNumber("") === 0
. Eventually, it returns true.Argument Type | Result |
---|---|
undefined |
false |
null |
false |
boolean |
same as input |
number |
+0 , -0 , NaN -> false , otherwise -> true |
string |
empty string -> false , otherwise -> true |
object |
true |
Array
is type of object
, the fact that an empty Array
is conversed to true
is correct.[] == false
is right.bool = !!array
code can be changed bool = array == false
.array === undefined
or array.length === 0
. π₯Personal blog by Jon Jee.
I hope to explain with words and code.