JavaScript ES6 (ECMAScript 6) introduced the spread operator. It expends the array in individual elements. The syntax is three-dot(...) before the item you want to spread.
The following are the very common uses by which you can improve the coding and make the task in a very short way.
An array can be easily copied with spread operator as shown below. Earlier Array.prototype.slice was used to copy an existing array.
Without spread operator
let fruits = ['Banana', 'Apple', 'Orange'];
let newFruits = fruits.slice();
With spread operator
concat() is used to concat two array, You can also use spread operator for the same task.
Without spread operator
With spread operator
There are methods like push and unshift which normally use to add an element at the end and beginning of the array. The same task can be performed with Spread operator:
Without spread operator
With spread operator
You can also use math functions with the spread operator. Let's have an example of Math function:
Math.max(50, 30, 40);
// will output 50
Without spread operator
For performing the same task on an array below is the way:
let arr = [20, 60, 90, 30, 10];
function max(arr) {
return Math.max.apply(null, arr);
}
console.log(max(arr)); // output will be 90
With spread operator
let arr = [10, 30, 20, 80, 60,100];
let max = Math.max(...arr);
console.log(max); // output will be 100
Without spread operator
let fruits = ['Banana','Orange','Apple'];
let getFruits = (arg1, arg2, arg3) => {
console.log(Fruits: ${arg1}, ${arg2} and ${arg3}
); };
With spread operator
let fruits = ['Banana','Orange','Apple'];
getFruits(...fruits); // Fruits: Apple, Orange and Banana
A string can also be converted to an array with spread operator.
Without spread operator
let str = 'fruits';
console.log(str.split('')); //will output ["f", "r", "u", "i", "t", "s"]
With spread operator
let str = "fruits";
let newStr = [...str];
console.log(newStr); // will output ["f", "r", "u", "i", "t", "s"]
Use of spread operator makes the task easier and shorter. ES6 has made JavaScript more efficient than earlier.
Click here to see Node.js Sample Application to get started for enterprise-level application.
Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.
Thank You!