Have you ever seen a weird code piece that contains something like [...array, el_1, el_2] or ever seen something that contains these 3 dots in Javascript? If you had seen such a thing and found yourself in this blog post, I’ll make your curiosity fade away.
Table of Contents
Spread Operator a.k.a 3 Dots in Javascript
In simple words, the spread operator, which is known as triple dots, expands the variable that is placed right after. For example, let’s say we have an array and we want to expand this or copy this in other words to another array. We could create a for-loop for that and append every element to the new array, or instead, we can just use this useful spread operator.
let array_1 = [1, 2, 3] let array_2 = [...array_1] // Output: [1, 2, 3]
The spread operator was added with ES6 to Javascript.
Example Usage of Spread Operator
But where do we use this efficiently? Only for copying arrays? The answer is a huge NO. Believe it or not, the spread operator’s usage area is really wide. Lemme show you some of the most common usage examples of this great operator.
1. Merging Arrays
let array_1 = [1, 2, 3] let array_2 = ["a", "b", "c"] console.log([...array_1, ...array_2]) // Output: [1, 2, 3, 'a', 'b', 'c']
2. Passing Parameters
If we have a function that can accept multiple parameters, we can extract an array and pass it easily.
function sum(num1, num2) {
return num1 + num2;
}
let array = [2, 5];
console.log(sum(...array))
// Output: 7It can be useful for functions that can take an infinite amount of parameters.
function sum() {
const nums = arguments;
let sumOfNumbers = 0;
for (let num of nums) sumOfNumbers += num;
return sumOfNumbers;
}
let array = [2, 5, 10, 4, 5];
console.log(sum(...array))
// Output: 263. Merging Objects
Don’t make arrays fool you, spread operators can also be used for objects, and even for strings! Let’s give an example for merging objects:
const obj_1 = {
name: "Ozan",
age: 19
}
const obj_2 = {
status: "Student",
country: "Turkey"
}
console.table({...obj_1, ...obj_2})
/** Output:
* name: 'Ozan'
* age: 19
* status: 'Student'
* country: 'Turkey'
*/4. Splitting Strings
const arr = [..."ABC"] console.log(arr); // Output: ['A', 'B', 'C']
Final Words
This was it for now, I tried to simplify the spread operator which is known as 3 dots in Javascript as much as I can. Stay tuned for further information about all of the operators in any programming language.