Module 3: Conditions and Loops
Truthy, Falsy, null, and undefined
Predict truthiness and distinguish absent values from valid falsy values.
JavaScript conditions convert values to booleans. Common falsy values include false, 0, -0, 0n, "", null, undefined, and NaN. Nearly everything else is truthy, including empty arrays and empty objects.
if ([]) console.log("An empty array is truthy");
if ({}) console.log("An empty object is truthy");
null versus undefined#
undefined commonly means a value was not assigned or a property is absent. null is often used to represent an intentional absence. Choose a consistent convention in your application rather than mixing both without a reason.
const profile = { nickname: null };
console.log(profile.email); // undefined: property does not exist
console.log(profile.nickname); // null: property exists with explicit absence
Default values#
Use || when any falsy value should trigger the fallback. Use ?? when only null and undefined should trigger it.
const suppliedLimit = 0;
const limitWithOr = suppliedLimit || 10; // 10
const limitWithNullish = suppliedLimit ?? 10; // 0
Use explicit checks when zero, an empty string, or false are meaningful values. Avoid vague truthiness checks for form values if the valid domain is more specific.
Practice#
Create a function that accepts an optional page size. Verify that 0 is preserved if it is a meaningful input, while null and undefined use a default.