JavaScript Truthy and Falsy
JavaScript does type conversion when evaluating various data types in Boolean contexts. For example:
const jedi = "Skywalker"
const name = jedi ? jedi : "No name"
The name
variable will be have Skywalker
string as its value because the jedi was evaluated as truthy. Other type of coercion, falsy, also happens when non Boolean data types which identified as false evaluated in Boolean context, for example:
const jedi = ""
const name = jedi ? jedi : "No name"
In the example above the name
variable value will be No name
because the jedi
was evaluated as false.
Examples of other truthy values:
if (true)
if ({})
if (\[\])
if (42)
if ("0")
if ("false")
if (new Date())
if (-42)
if (12n)
if (3.14)
if (-3.14)
if (Infinity)
if (-Infinity)
Examples of falsy values
if (false)
if (null)
if (undefined)
if (0)
if (0n)
if (NaN)
if ('')
if ("")
if (\`\`)
if (document.all)