Course contentsShow
← JavaScript
Lesson 964 of 2,72322. Spread and RestFree lesson

Spreading Strings into Arrays

Convert strings into arrays of characters using the spread operator.

Spreading Strings into Arrays

You'll learn how to split a string into an array of individual characters using the spread operator.

You already know how to spread arrays, but strings are also iterable in JavaScript. This means you can use the spread operator (...) to break a string apart into its individual characters, creating an array.

The Core Idea

When you spread a string, JavaScript iterates through each character and places it as a separate element in an array. Think of it like unzipping a word letter-by-letter and laying each letter out in its own box.

const word = "hello";
const chars = [...word];
console.log(chars); // ['h', 'e', 'l', 'l', 'o']

This is much cleaner than older methods and works seamlessly with the rest of JavaScript's modern syntax.

Why This Matters

Before the spread operator, you'd need methods like split('') to accomplish this:

const word = "hello";
const chars = word.split('');
console.log(chars); // ['h', 'e', 'l', 'l', 'o']

Both work, but the spread operator is more consistent with how you handle other iterables. You can also combine it with other array operations:

const greeting = "Hi!";
const exclamations = [...greeting, '!', '!'];
console.log(exclamations); // ['H', 'i', '!', '!', '!']

Real-World Use Cases

This technique is handy for character manipulation, counting specific letters, or reversing strings:

const name = "Anna";
const reversed = [...name].reverse();
console.log(reversed); // ['a', 'n', 'n', 'A']

Key Takeaway: Use the spread operator (...) on strings to quickly convert them into arrays of individual characters, making character-level operations simpler and more readable.