Back to TIL

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

JavaScript
const [first, second = 'default', third] = ['a'];
// first = 'a'
// second = 'default'
// third = undefined

This is useful when you’re not sure if an array has enough elements, but you want to provide fallback values.

Real-World Example

JavaScript
function processUserData([name, email = 'no-email', age]) {
  console.log(name, email, age);
}
 
processUserData(['John']);
// Output: John no-email undefined

Simple but powerful!