The Rest parameter and the Spread operator made simple. Part 2
All you need to know about the spread operator in JavaScript
In part 1, we covered a lot about the rest parameter. We learned the rest parameter is denoted by three dots ...
followed by the name of the array to pack the incoming arguments. We discovered that the rest parameter gathers all the incoming arguments into an array.
Now let's learn in detail the spread operator.
Introduction
The spread operator is one of the features introduced in ES6. It gives you the power to access the internals of iterables. An iterable is a datatype whose elements can be iterated over for example strings, object literals and arrays. The spread operator breaks down an iterable data type into individual elements that make it and expands or spread the elements of that iterable where arguments are expected. It also expands the elements of an array or object where elements separated by commas are expected.
Basics of the spread operator
The spread operator, as we have discussed above, helps us have access to the individual elements of an iterable like arrays, strings, and literal objects. The example below can help us demonstrate what that means.
const language = ["English", "Swahili", "Luganda"];
const languages = [...language];
console.log(languages);
Running console.log(languages)
should print the following
[ 'English', 'Swahili', 'Luganda' ]
The languages
array looks exactly like the language
array. Essentially, the spread operator has copied all of the elements of the language
array to the languages
array.
We ought to be careful to always put the spread operator inside brackets [...language]
because in case we forget, the console will throw to us an error. For example
const language = ["English", "Swahili", "Luganda"];
const languages = ...language;
console.log(languages);
SyntaxError: Unexpected token '...'
Clone a literal object using the spread operator
Using the spread operator, it is easy and painless to copy an object into another. There are other ways to do this, but the spread operator makes it joyfully easy. We use the spread operator to copy object literals as we did in arrays.
const hello = {
english: "Hello",
swahili: "Habari",
luganda: "Nkulamusiza"
};
const greet = { ...hello };
console.log(greet)
Running console.log(greet)
will give us the output below
{ english: 'Hello', swahili: 'Habari', luganda: 'Nkulamusiza' }
Merge iterable objects with the spread operator
The spread operator can be used to combine two or more iterable objects into one.
const foreign = ["English", "French", "Chinese"];
const local = ["Luganda", "Rukiga", "Lusoga"];
const allLanguages = [...foreign, ...local];
console.log(allLanguages)
Elements of foreign
and local
are now combined into allLanguages
as a single array. The output is seen below
[ 'English', 'French', 'Chinese', 'Luganda', 'Rukiga', 'Lusoga' ]
You can also add a 'spreaded' array inside another array where comma-separated elements are expected.
const foreign = ["English", "French", "Chinese"];
const allLangugaes = [...foreign, "Rukiga", "Lusoga"];
console.log(allLangugaes)
Now, allLanguages
consists of elements from foreign
[ 'English', 'French', 'Chinese', 'Rukiga', 'Lusoga' ]
We merge two or more objects into one object the same way we merge arrays using the spread operator.
const hello1 = {
english: "Hello",
swahili: "Habari",
};
const hello2 = {
french: "salut",
spanish: "Hola"
};
const greet = {...hello1, ...hello2};
console.log(greet);
The spread operator will get the internals of hello1
and hello2
and combine them to form a single object greet
as shown below
{ english: 'Hello', swahili: 'Habari', french: 'salut', spanish: 'Hola' }
Programmers can also use Object.assign()
to merge two objects into one, but the spread operator makes it so simple and neat.
Spreading arguments
If you want to use elements of an array as arguments of a function, you are free to use the spread operator as shown below.
function addNums(num1, num2,num3) {
const sum = num1 + num2 + num3;
return sum;
}
const arrayOfNums = [5, 10, 15];
console.log(addNums(...arrayOfNums));// 30
Sometimes programmers use apply
to achieve the same result as above, but the spread operator can be used in situations where apply
is not appropriate.
The spread operator and strings
Strings are iterable, you can use the spread operator to access individual elements of a string. Let's see an example
const name = "Seremba";
const spellName = [...name]
console.log(spellName)
The varibale name
is broken down into individual characters.
['S', 'e', 'r','e', 'm', 'b','a']
Conclusion
The spread operator is a lifesaver, you can accomplish a lot of common tasks with it and with this tutorial, you now know how to use it. If you want to dig deeper into the topic(spread operator), MDN documentation can be of great help.