Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Array destructuring is a shortcut to extract values from arrays and assign them to variables. Instead of arr[0], arr[1], you can unpack them all at once!
arr[0], arr[1]), you lay them all out at once with labels!const colors = ['red', 'green', 'blue']; const first = colors[0]; const second = colors[1]; const third = colors[2];
const colors = ['red', 'green', 'blue']; const [first, second, third] = colors; // first = 'red' // second = 'green' // third = 'blue'
Extracting values from arrays
Leave empty slots with commas to skip elements you don't need
const colors = ['red', 'green', 'blue', 'yellow']; // Skip green and blue, only get red and yellow const [first, , , fourth] = colors; console.log(first); // 'red' console.log(fourth); // 'yellow'
Get only what you need
Use = to set default values in case elements are missing
const colors = ['red']; // Without defaults const [first, second] = colors; console.log(second); // undefined // With defaults const [a, b = 'green'] = colors; console.log(b); // 'green'
Handling missing array elements
Use ... to gather remaining elements (must be last!)
const numbers = [1, 2, 3, 4, 5]; const [first, second, ...rest] = numbers; console.log(first); // 1 console.log(second); // 2 console.log(rest); // [3, 4, 5]
Gathering remaining elements
let a = 1; let b = 2; // Need temp variable let temp = a; a = b; b = temp;
let a = 1; let b = 2; // One line swap! [a, b] = [b, a];
Quick variable swaps
Use nested brackets to destructure nested arrays
const matrix = [[1, 2], [3, 4]]; const [[a, b], [c, d]] = matrix; console.log(a, b, c, d); // 1 2 3 4
Working with multi-dimensional arrays
Destructure directly in function parameters or return values
// Function parameter destructuring
function printCoords([x, y]) {
console.log(`X: ${x}, Y: ${y}`);
}
printCoords([10, 20]); // X: 10, Y: 20
// Return value destructuring
function getMinMax(arr) {
return [Math.min(...arr), Math.max(...arr)];
}
const [min, max] = getMinMax([5, 2, 8, 1, 9]);
console.log(min, max); // 1 9Clean function signatures and returns
[a, b] = [b, a]x, y, zconst [a, b, c] = arrayconst [a, , c] = arrayconst [a = 1, b = 2] = arrayconst [first, ...rest] = array[a, b] = [b, a]const [state, setState] = useState(0) - this is array destructuring in action!