Spread and Rest Operators
Introduction: Same Syntax, Different Jobs
In our previous lesson, we looked at how to use the "rest" syntax within destructuring to collect the remaining items of an array. You might have noticed that we used three dots (...) to do that. Today, we are going to explore this syntax in much more detail. In modern JavaScript, these three dots have two distinct roles depending on where you use them: they either "spread out" data or "gather up" data.
When we use this syntax to expand an array or an object into a new one, we call it the spread operator. When we use it to collect multiple values into a single variable, we call it rest parameters. Understanding the difference between these two is a major step in writing clean, professional code. As always, the examples we cover today will work perfectly in your CodeSignal IDE, where the environment is already set up for you.
Spreading Arrays
The most common use for the spread operator is working with arrays. Imagine you have two separate lists of numbers and you want to join them into one larger list. In the past, this required using specific array methods that could be difficult to read. With the spread operator, you can "pour" the contents of one array into another.
Output:
In this code, the merged array is created by spreading out all the elements from array a and all the elements from array b. Notice that we also added the number 6 at the very end. The spread operator essentially takes the items out of their original containers and places them individually into the new array. This is an excellent way to combine data or add new items to a list without modifying the original variables.
Spreading Objects
Just as we can spread arrays, we can also spread objects. When you spread an object into a new one, JavaScript takes all the key-value pairs from the source object and copies them into the new one. This is a very fast way to create a shallow copy of an object.
A shallow copy means that only the top-level properties are copied. If the original object contains nested objects or arrays, the new copy will still point to those same nested items in memory rather than creating brand-new versions of them.
Output:
In this example, the copy object starts with everything inside the original object. By adding location after the spread operator, we create a new object that has three properties instead of two. This technique is incredibly helpful because it allows us to build new data structures based on existing ones with very little code.
