Data Structures: The Spread Operator (...)
Part 3: A guide to destructure objects in JavaScript
This feature blew up my mind 🤯, at the beginning, I didn't understand what was this about, until I started using it and I studied a little bit more about its use. I recall you that I made a synthesis from the Jonas' course, which I recommend you to check out and extra resources like MDN.
🤷 What is this for?
The spread operator is used to expand elements from one array to a new array or object. Simple like that.
Without this operator, creating new arrays from existing ones will be very difficult, let's see some examples.
Let's say we have two arrays with some elements and we want to combine them in one array. As a JavaScript beginner I could think of the following solution:
const array_1 = [1, 2, 3];
const array_2 = [4, 5, 6];
const newArray = [array_1 + array_2];
But definitely, that's something we don't want, it'll give us a string as a value and they're not separated:
const newArray = [array_1 + array_2];
console.log(newArray);
// ["1,2,3 4,5,6"]
Or maybe just adding some values and then the array I want to add, but that won't work either, because they will still be separated.
const newArray = [1, 2, 3, array_2]
console.log(newArray)
// [1, 2, 3, [4, 5, 6]]
A real solution is to add every element of that array, we can also loop over elements.
// ADDING ARRAY ELEMENTS MANUALLY
const newArray = [array_1[0], array_1[1], array_1[2],array_2[0], array_2[1],array_2[2]];
console.log(newArray);
// [1, 2, 3, 4, 5, 6]
// OR USING A FOR LOOP
let newArray = [];
for(let i = 0; i < array_1.length; i++){
newArray.push(array_1[i]);
}
for(let j = 0; j < array_2.length;j++){
newArray.push(array_2[j]);
}
console.log(newArray);
// [1, 2, 3, 4, 5, 6]
But that's too many lines of code that can now be simplified with the spread operator. The only thing you need to do is add it to your new array and it's done.
const newArray = [1 , 2 , 3, ...array_2];
console.log(newArray);
// [1, 2, 3, 4, 5, 6]
That's cleaner than doing extra calculations. All the values are taken out of their arrays and they are added individually as if we were doing it manually. You can also use the spread operators in as many elements you'd like to add:
const newArray = [...array_1, ...array_2]
✅ Copy of an array
Copying an array is not doing Ctrl + C and Ctrl + V. There are some cases in which we may need to modify the values of an array, but we also need to keep the values of that array intact, because it's used in a different function or depending on your needs.
So, we have this array and we want to create a copy of this, we do the following:
const cars = ['toyota', 'nissan', 'honda', 'hyundai', 'kia'];
const myCars = [...cars];
Now we can do any change in the myCars
array since it works as a shadow copy and keeps cars intact.
✅ Concatenate two arrays
You can use the great method of .concat()
however the spread syntax makes this easier, as we previously saw it with the example:
const newArray = [...array_1, ...array_2]
✅ Can I use it with strings?
We confirmed that the spread operator is very useful in arrays, where there are multiple values, but would the spread operator work on a string? Yes, it will.
Strings are iterable objects in which we can define or customize their iteration, in plain English, we can create functions or do any operation with each element of their value (Iteration protocols is an interesting topic, I'll research about it and I'll summarize ideas soon).
So, for example, we have our string 'David'
and since it's iterable, I can loop over each letter and execute a method or a function and that's how we use the spread syntax.
const myName = 'David';
const spelling = [...myName];
console.log(spelling);
// ["D", "a", "v", "i", "d"]
That's a cool feature because it makes everything easy. Just as a reminder, it's that you can only use the spread operator in scenarios where we can add multiple elements separated by commas like an array or a function.
With that being said, it's not possible to spread a string in template literals:
const myName = 'David';
console.log(`My name is ${myName} and it spells ${...myName}`);
// Uncaught SyntaxError: Unexpected token '...'
That happens because the embedding expression is not a place to add multiple values separated by commas.
✅ Spread operator as function arguments
The spread operator works as destructuring elements of an array or an object, the difference is that the spread operator takes all the elements from the array but it doesn't create a new variable, so we need to only use it in places where we write values separated by commas.
That's why we can use the spread operator as an argument of a function because remember that spreading values means adding multiple elements individually.
const colors = ['red', 'blue', 'green'];
function favoriteColors(color1, color2, color3){
console.log(`My favorite colors are ${color1}, ${color2}, and ${color3}`);
}
favoriteColors(...colors);
// My favorite colors are red, blue, and green
We didn't need to do something like function(colors[0], colors[1], colors[2])
and that's why it's very useful to spread values, it is a great update, because it follows the DRY principle (Don't Repeat Yourself), making things clearer and organized in your .js file.
Spread syntax on objects(?)
As per MDN, once the spread operator was created, it was intended to only work on iterables, and objects are not iterable, so you couldn't use it, but after ES2018, you can now use it with object properties.
So feel free to make shadow copies of the properties of your objects into new ones. Let's check the example from the previous blog post
const sellers = {
asia: 'VendorA',
america: 'VendorB',
europe: 'VendorC'
}
const vendors = {...sellers}
console.log(vendors);
// {asia: "VendorA", america: "VendorB", europe: "VendorC"}
Or you can also integrate the properties of the object in a new one, so their values will expand.
const nissan = {
name: 'Nissan',
model: 'Sentra',
year: 2015,
color: 'black',
isAutomatic: false,
...sellers
}
Technology is fascinating and how it's being improved every day, hope you enjoyed and learned something today, see you in the next one.