In JavaScript, the following values are considered falsy:
- Boolean
false
; - Numbers
0
,0.0
and0x0
(including their negative counterparts — i.e.-0
,-0.0
and-0x0
); NaN
;BigInt
0n
(or0x0n
);- Empty String (i.e.
''
,""
and``
); null
undefined
;- Objects with the
[[IsHTMLDDA]]
internal slot (which only exists indocument.all
and cannot be set using JavaScript).
These values evaluate to a boolean false
when:
- They're explicitly converted to a boolean (for example by using double negation
!!
or theBoolean
object wrapper); - Certain contexts require type conversion to boolean (such as in conditionals and loops) — in which case the value is coerced to a boolean implicitly/automatically.
Consider for example, the following (where the falsy values are coerced to boolean false
inside the if
block):
// boolean if (false)
// number if (0) if (0.0) if (0x0) if (-0) if (-0.0) if (-0x0) if (NaN)
// BigInt if (0n) if (0x0n)
// string if ('') if ("") if (``)
// nullish value if (null) if (undefined)
// object if (document.all)
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.