Destructuring Strings as Iterables
What you'll learn: How to use array destructuring to pull individual characters out of a string.
You've learned that array destructuring lets you extract values from arrays into separate variables. Here's something cool: strings are iterable in JavaScript, which means you can destructure them exactly like arrays to grab individual characters.
The Core Idea
When you destructure a string, JavaScript treats it as a sequence of characters. Each position in the string can be assigned to a variable, just like extracting elements from an array.
const word = "Hello";
const [first, second] = word;
console.log(first); // "H"
console.log(second); // "e"
Think of a string like a necklace of beads. Destructuring lets you pick off the first bead, second bead, and so on, assigning each to its own container.
Practical Examples
You can use all the destructuring patterns you've learned:
// Skip characters with commas
const [first, , third] = "ABC";
console.log(first, third); // "A" "C"
// Grab the rest with the spread operator
const [initial, ...restOfWord] = "JavaScript";
console.log(initial); // "J"
console.log(restOfWord); // ["a", "v", "a", "S", "c", "r", "i", "p", "t"]
// Use default values if the string is too short
const [a, b, c = "!"] = "Hi";
console.log(a, b, c); // "H" "i" "!"
Notice that when you use the rest operator, you get an array of the remaining characters, not a string.
Key Takeaway: Since strings are iterable, you can destructure them like arrays to extract individual characters—useful for parsing initials, analyzing text structure, or pulling specific character positions.