JavaScript Interview Question #12
What are truthy and falsy values in JavaScript?
JavaScript Fundamentals, Types, Scope & Functions Junior Beginner
Quick Interview Answer
In a Boolean context, JavaScript converts values to true or false. Falsy values include false, 0, -0, 0n, an empty string, null, undefined, and NaN. Most other values are truthy, including empty arrays and empty objects.
Detailed Explanation
In a Boolean context, JavaScript converts values to true or false. Falsy values include false, 0, -0, 0n, an empty string, null, undefined, and NaN. Most other values are truthy, including empty arrays and empty objects.
Truthy and falsy behavior is frequently used in conditions, logical operators, defaulting logic, and validation. A common mistake is assuming an empty array or empty object is falsy; both are truthy.
Code Example
if ("hello") {
console.log("Truthy");
}
if (!0) {
console.log("0 is falsy");
}
console.log(Boolean([])); // true
console.log(Boolean({})); // true
console.log(Boolean("")); // false