9 types of falsy values in JavaScript
Ever wondered what is considered falsy in JavaScript. Here is the complete list of all the possible falsy values in JavaScript.
You might have already come across (or may come across) the question below in a JavaScript/Frontend/Web Engineer interview.
What are the possible outcomes of the given code snippet?
function greet(value) {
if (value) {
return "Hello, World!";
}
return value;
}
To answer the above question, you first need to understand what is considered falsy in JavaScript. Before continuing with the post, take a while and try to answer this by yourself. Let me know your answers in the comments below.
Falsy values in JavaScript -
null
The null value represents the absence of any value.
Boolean(null) // false
undefined
The undefined property indicates that a variable has not been assigned a value, or not declared at all.
Boolean(undefined) // false
false
The boolean value.
NaN
The global property that represents Not-A-Number.
Boolean(NaN) // false
0
The number zero (including 0.0, 0x0).
Boolean(0) // false
-0
The number negative zero (including -0.0, -0x0)
Boolean(-0) // false
0n
The BigInt zero (including 0x0n). BigInt values represent numeric values which are too large to be represented by the number.
Boolean(0n) // false
""
The empty string value (including '' and ``).
Boolean("") // false
document.all
The only falsy object in JavaScript. This read-only property returns HTMLAllCollection rooted at the document node. This property is deprecated, some browsers might still support it.
Boolean(document.all) // false
So in total there are 9 falsy values in JavaScript and all other values are considered truthy.
Answer to the above question -
Above code snippet have 10 possible outcomes (9 falsy values and "Hello, World!" for all other values).