Problem Statement
What will be the output? const {a, b, c = 3} = {a: 1, b: 2}; console.log(c);
Explanation
Destructuring with default values assigns the default when the property is undefined or does not exist.
In this case, the object does not have a c property, so c gets the default value of 3.
Default values only apply when the value is undefined, not when it is null or any other falsy value.
This pattern is useful for providing fallback values when destructuring objects.
Destructuring with defaults is commonly used in function parameters and API responses.
Understanding default values in destructuring prevents bugs from missing properties.
Code Solution
SolutionRead Only
// Object destructuring with defaults
const {a, b, c = 3} = {a: 1, b: 2};
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3 (default value)
// Default only used when undefined
const {x = 10} = {x: 0};
console.log(x); // 0 (not 10, because 0 is defined)
const {y = 10} = {y: null};
console.log(y); // null (not 10, because null is defined)
const {z = 10} = {z: undefined};
console.log(z); // 10 (undefined triggers default)
const {w = 10} = {};
console.log(w); // 10 (missing property)
// Array destructuring with defaults
const [first, second, third = 3] = [1, 2];
console.log(third); // 3
// Nested destructuring with defaults
const user = {
name: 'John',
address: {
city: 'NYC'
}
};
const {
name,
address: {city, zip = '00000'}
} = user;
console.log(city); // 'NYC'
console.log(zip); // '00000' (default)
// Function parameters with destructuring
function greet({name, greeting = 'Hello'}) {
console.log(`${greeting}, ${name}`);
}
greet({name: 'John'}); // 'Hello, John'
greet({name: 'Jane', greeting: 'Hi'}); // 'Hi, Jane'
// Common pattern in React
function Component({title, count = 0, onSubmit = () => {}}) {
// Use props with defaults
}