javascriptintermediate10 minutes
Predict the Output of Nested Array and Object Destructuring with Defaults
Analyze the given JavaScript code involving nested array and object destructuring with default values and predict the final output.
Challenge prompt
Consider the following JavaScript snippet. Predict the output printed to the console without running the code: const data = [ { id: 1, values: [10, 20] }, { id: 2 }, { id: 3, values: [30] } ]; const [ { values: [a, b] = [0, 0] }, { values: [c, d] = [5, 5] }, { values: [e, f] = [7, 7] } ] = data; console.log(a, b, c, d, e, f); What values are logged to the console?
Guidance
- • Review how destructuring assignment works with nested arrays and objects
- • Recall that default values in destructuring only apply when the property being destructured is undefined
- • Look at each element of 'data' and consider what happens when that element does or does not have the 'values' property
Hints
- • For the second object in the array, 'values' is missing, so the default array [5,5] is used during destructuring
- • For the first object, 'values' is present, so the default [0,0] is ignored
- • Remember that when destructuring arrays, missing elements default to 'undefined' unless a default is provided
Starter code
const data = [
{ id: 1, values: [10, 20] },
{ id: 2 },
{ id: 3, values: [30] }
];
const [
{ values: [a, b] = [0, 0] },
{ values: [c, d] = [5, 5] },
{ values: [e, f] = [7, 7] }
] = data;
console.log(a, b, c, d, e, f);Expected output
10 20 5 5 30 undefined
Core concepts
JavaScript destructuringdefault values in destructuringarrays and objects
Challenge a Friend
Send this duel to someone else and see if they can solve it.