JavaScript2 min read
Destructuring with Default Values
Avoid undefined errors with smart destructuring defaults
S
Shahar Amir
Destructuring with Default Values
API returned incomplete data? Props missing? Defaults have your back.
Basic Defaults
javascript
12345
const user = { name: "John" };
const { name, age = 25 } = user;// name: "John"// age: 25 (default used)Function Parameters
javascript
1234567891011121314
// ❌ Old wayfunction greet(options) { const name = options.name || "Guest"; const formal = options.formal || false;}
// ✅ Better wayfunction greet({ name = "Guest", formal = false } = {}) { console.log(formal ? `Hello, ${name}` : `Hey ${name}!`);}
greet(); // "Hey Guest!"greet({ name: "John" }); // "Hey John!"greet({ name: "John", formal: true }); // "Hello, John"The = {} at the end handles when no argument is passed at all.
Nested Defaults
javascript
12345678910
const config = { api: { timeout: 5000 }};
const { api: { timeout = 3000, retries = 3 } = {}} = config;
// timeout: 5000 (from config)// retries: 3 (default)Array Destructuring
javascript
123456
const [first = 0, second = 0] = [1];// first: 1// second: 0 (default)
// Useful for split resultsconst [name, extension = "txt"] = filename.split(".");Renaming + Defaults
javascript
1234
const user = { name: "John" };
const { name: userName = "Anonymous" } = user;// userName: "John"Real-World Example
javascript
12345678910111213
function fetchData({ url, method = "GET", headers = {}, timeout = 5000, retries = 3,} = {}) { // All params have sensible defaults}
// Clean API callsfetchData({ url: "/api/users" });fetchData({ url: "/api/data", method: "POST", timeout: 10000 });Stop checking for undefined manually. Let destructuring defaults do the work.
#destructuring#es6#patterns
Stay Updated 📬
Get the latest tips and tutorials delivered to your inbox. No spam, unsubscribe anytime.