Code Snippets library
5 Ways to Set Default Value
// 1. Logical OR (||) - falsy values become default
// falsy values: 0, "", false, NaN, null, undefined
let name = inputName || "John";
// 2. Nullish coalescing (??)
// Only null and undefined are replaced
let name = inputName ?? "John";
// 3. Ternary operator
let name = typeof inputAge !== "undefined" ? name : "John";
// 4. Function parameters with defaults (ES6+) - BEST for functions
function createUser(name = "John", age = 18, isActive = true) {
return { name, age, isActive };
}
// 5. Destructuring with defaults – GREAT for objects
const config = { firstName: "Alice" };
const {
firstName = "John",
lastName = "Doe",
nickname = "N/A"
} = config;
const names = { firstName, lastName, nickname };
console.log(names)
// Output: { firstName: "Alice", lastName: "Doe", nickname: "N/A" }