Array Destructuring with Default Values
Published on
javascripttil
Array Destructuring with Default Values
Today I learned that you can use default values in array destructuring, similar to object destructuring.
The Trick
const [first, second = 'default', third] = ['a'];
// first = 'a'
// second = 'default'
// third = undefinedThis is useful when you’re not sure if an array has enough elements, but you want to provide fallback values.
Real-World Example
function processUserData([name, email = 'no-email', age]) {
console.log(name, email, age);
}
processUserData(['John']);
// Output: John no-email undefinedSimple but powerful!