6.8 The Spread Operator
So in the last video, you learned how to use the concat method to combine two arrays. Now there is another way to do the same thing using the broadcast operator in ES6. So I'm going to rewrite this code using the broadcast operator and you'll see why this approach is cleaner and more flexible. So, I'm going to define a variable that we're going to call Combined as a new array, now we want to combine all the elements of the first array and the second array. So we use the spread operator like this. First then second. When we distribute an array, all its elements are distributed individually. So, basically, we declare a new array, and into that array, we add the individual elements of the first and second arrays. So this piece of code here is exactly like this. So we can see with the broadcast operator, we have a better visualization of how these arrays are combined. It's very clear that we have an array and in that array, we have all the elements of the first array, followed by all the elements of the second array. Now, with this scatter operator, we have more flexibility, let's say as part of the combination of these two arrays, we want to add an element in between them, you can do it easily like that. Or we can add something at the end. Again, we can see clearly what the combined array looks like. On the other hand, if you want to do the same thing using the concat method, our code is going to be more complex. So here's how we can use the broadcast operator to combine two arrays. In the last video, you learned that if you call the slice method without any arguments, it will return a copy of the original array here. So let's call that copy, we can again use the spread operator to copy all the elements of an array into a new array. So we can rewrite this code like this. Constant, copy, we create a new array, then spread the combined array. So this will return all the elements of the combined array and place them in this new area. That's it for this video on the Spreading Operator in JavaScript, we'll see you in a very next video.