Default Values in Array Destructuring
You'll learn how to provide fallback values when destructuring array positions that might be missing or undefined.
The Core Idea
When destructuring an array, you might try to extract more values than the array actually contains. Without default values, those variables would be undefined. JavaScript lets you specify fallback values that will be used if the array position doesn't exist or is explicitly undefined.
Think of it like ordering from a menu with substitutions: "I'll have the third item, but if they're out, give me a salad instead."
How It Works
You assign default values using the = operator right in the destructuring pattern:
const colors = ['red', 'blue'];
// Without defaults - third variable is undefined
const [first, second, third] = colors;
console.log(third); // undefined
// With defaults - third gets fallback value
const [a, b, c = 'green'] = colors;
console.log(c); // 'green'
When Defaults Activate
Defaults only kick in when the value is undefined or doesn't exist. They do not activate for null or other falsy values:
const data = ['hello', undefined, null];
const [x = 'default1', y = 'default2', z = 'default3'] = data;
console.log(x); // 'hello' (value exists)
console.log(y); // 'default2' (undefined triggers default)
console.log(z); // null (null does NOT trigger default)
Practical Use
This is incredibly useful when working with functions that might return incomplete arrays or when processing data where some positions are optional.
Key Takeaway: Default values in array destructuring provide fallback values for positions that are undefined or don't exist, making your code more resilient when dealing with incomplete or variable-length arrays.