Instructor: 00:00 In this example, I have a house-animals array and a farm-animals array, which I'm rendering to the screen using React. House and farm. What I'd like to do is merge my two arrays into one and render it to the screen below.
00:15 First of all, we'll do this the old school way, which is still valid. We'll create a variable called animals and we'll concat the two. We'll say house-animals concat farm-animals. Then we'll add a div and we'll say animals, animals. Looks like my list has been concatenated and we're good to go.
00:37 Another way to perform the same thing is to use the spread syntax. I'm going to go and create another animals array coming off this one. Instead of concatenating house-animals with farm-animals, I'm going to create a new array, and we're going to spread over house-animals and farm-animals.
00:55 This ... syntax that we're looking at here is the same syntax that we used for rest and spread. That's what people can get a little confused. In this case, we are spreading over each of the items that are found in this array.
01:07 In other words, we are itemizing the elements in this array and appending it to the new array, giving us the same result that we had before with our concat example. That's the spread syntax. Let's go ahead and look at rest now.
01:17 Let's say I wanted to extract the first two animals in our new array to some variables, and the rest of the array into its own variable. I can do that with a combination of destructuring and the rest operator.
01:28 The first thing I'm going to do is destructure the first two items in this array. We'll say const dog and cat. Next, I'm going to use the rest syntax, which acts as a container for the rest of the elements in the array that I'm not destructuring or pulling off of it, and then assign it to animals to make it work.
01:47 Now, to test it out. I'm going to copy my animals div here and paste it below. We're going to say dog and replace this with dog. Then we're going to cute cat, replace this with cat. Then we're going to go ahead and render the rest of our animals. We're going to say rest and rest. It looks like it works. I have a dog, cat, and the rest of the animals that are in the array.
02:12 That's a quick explanation of the difference between rest and spread. Both use the ... syntax, but one is for spreading over items, and one is for containing items. This syntax is used a lot for manipulating arrays as well as objects.
02:26 If I wanted to combine two objects together, I can simply spread over them and assign it to a new variable.