Problem Statement
What does this code do: const [a, b] = [1, 2, 3]?
Explanation
Array destructuring extracts values from arrays into distinct variables.
It assigns values by position. Extra values in the array are ignored. Missing values become undefined.
You can skip elements using commas, swap variables, or use rest operator to collect remaining elements.
Destructuring makes code cleaner when working with arrays.
It was introduced in ES6 and is widely used in modern JavaScript.
Code Solution
SolutionRead Only
// Basic destructuring const [a, b] = [1, 2, 3]; console.log(a); // 1 console.log(b); // 2 // 3 is ignored // Missing values are undefined const [x, y, z] = [1, 2]; console.log(z); // undefined // Skip elements const [first, , third] = [1, 2, 3]; console.log(first); // 1 console.log(third); // 3 // Rest operator const [head, ...tail] = [1, 2, 3, 4, 5]; console.log(head); // 1 console.log(tail); // [2, 3, 4, 5] // Swap variables let num1 = 10; let num2 = 20; [num1, num2] = [num2, num1]; console.log(num1); // 20 console.log(num2); // 10 // Default values const [p = 1, q = 2] = [5]; console.log(p); // 5 console.log(q); // 2 (default) // Nested destructuring const [m, [n, o]] = [1, [2, 3]]; console.log(m, n, o); // 1 2 3
