JavaScriptEasy
What is truthy and falsy?
Every value in JavaScript becomes true or false when used in a boolean context; the falsy values are false, 0, -0, 0n, "", null, undefined and NaN, and everything else is truthy.
Boolean contexts
if, while, the ternary ? :, &&, ||, !, and Boolean(value) all convert their operand to a boolean.
Surprising truthy values
"0"and"false": non-empty strings are truthy.[]and{}: all objects are truthy, even empty ones.new Boolean(false): an object, so truthy.-1,Infinity: any non-zero number is truthy.
Why it matters
Truthiness makes short checks convenient (if (user)), but can hide bugs when 0 or "" are valid values:
if (count)is false whencountis0.value || "default"replaces a legitimate0or"".
Safer patterns
- Use
??when onlynull/undefinedshould get a default. - Check emptiness explicitly:
array.length === 0,Object.keys(obj).length === 0,str.trim() === "". - Use
value != nullto mean "has a value", including0and"".
Converting explicitly
Boolean(x) or !!x produce a real boolean, useful when an API expects true/false (for example a React prop like disabled).
Code example
js
1const falsy = [false, 0, -0, 0n, "", null, undefined, NaN];2console.log(falsy.map(Boolean)); // all false34const surprisinglyTruthy = ["0", "false", " ", [], {}, -1, Infinity];5console.log(surprisinglyTruthy.map(Boolean)); // all true67// The bug: 0 is a valid quantity8const quantity = 0;9if (quantity) console.log("has items");10else console.log("treated as empty!"); // runs - probably not intended1112// Defaults: || vs ??13const volume = 0;14console.log(volume || 50); // 50 - wrong, 0 was valid15console.log(volume ?? 50); // 0 - correct1617// Explicit emptiness checks18const list = [];19console.log(list ? "truthy" : "falsy", list.length === 0 ? "empty" : "has items"); // truthy empty2021// Real booleans for APIs that need them22const isDisabled = !!"";23console.log(isDisabled, typeof isDisabled); // false "boolean"
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.