SyntaxStudy
Sign Up
JavaScript Intermediate 4 min read

Destructuring Iterables

Destructuring Any Iterable

Array destructuring works on any iterable: strings, Sets, Maps, generators, and NodeLists.

Example
const [a, b, c] = "abc"; // a="a" b="b" c="c"
const [first] = new Set([10, 20, 30]); // 10
const [[k, v]] = new Map([["x", 1]]); // k="x" v=1
function* gen() { yield 1; yield 2; yield 3; }
const [one, two] = gen(); // one=1 two=2
const [head, ...tail] = document.querySelectorAll("li");
Pro Tip

Any object implementing Symbol.iterator can be destructured with array syntax.