Spread Operator

Learn about using the spread operator on strings.

We'll cover the following

We’re now a good three-quarters of the way through this course and well on our way to learning how to code. In fact, we already know enough to be able to write some short programs.

Now that we’ve learned the basics, it’s time to dive a bit deeper into some more advanced topics in the last quarter of the course. The last few chapters will focus on some of the more specific parts of JavaScript—although a lot of the overarching concepts will still apply in other languages.

Let’s start with learning about how to iterate over collections, such as arrays and objects.

Spreading strings

The spread operator (...) can be used in JavaScript to spread out the items of an array when the array is placed inside another array.

The spread operator can also be used to spread out all the characters of a string inside an array. Each character of the string becomes an individual item in the array:

Press + to interact
console.log([..."Hello"]);

This can be a very useful technique because it allows us to use array methods on a string. For example, we could reverse a string with the following code:

Press + to interact
console.log([..."Hello"].reverse().join(''));

Chaining methods

The code above uses chaining, which is the process of applying one method after another in a chain of method calls. Each subsequent method is called on the return value of the previous method. In the example above, the spread operator returns an array, then we immediately call the reverse() method on that array that returns another array, and then we immediately call the join() method on that array, which returns the final string. The following code snippets break down what’s happening in each step of the chain:

  1. The string starts as this:
"Hello";
  1. Then the spread operator is applied and returns the following array:
Press + to interact
console.log([..."Hello"]);
  1. Then the reverse() method is called to return the following array:
Press + to interact
console.log([..."Hello"].reverse());
  1. Finally, the join() method is called on the array to change it back to a string:
Press + to interact
console.log([..."Hello"].reverse().join(''));

Each of those steps happens one after the other without returning any of the intermediate values, so all we see is the final return value.

One particular benefit of using the spread operator on strings is that we can use iteration methods on them. So, what are iterators? Let’s talk about them in the next lesson.