Introduction
The evolution of JavaScript to the ES6 version has brought a whole array of new tools and utilities. One such new feature is the spread operator.
Spread operator
Spread operator allows an inerrable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected. JavaScript ECMAScript 6 introduced the spread operator. The operator’s shape is three consecutive dots and is written as:
Syntax
- var variablename = [...value];
Examples are given below.
- const nambers = [1, 2, 3 ,4 ,5 ,6 ,7 ,8 ,9 ,10];
console.log (...nambers);
-
Spread in function calls
- function Subtract (x, y, z) {
- return x * y * z;
- }
- const Subnumbers = [5,6,7,8];
- console.log (Subtract (...Subnumbers));
-
Spread in array literals
- var one = ['Ravi', 'Vicky'];
- var two = ['mohit', ...one, 'and', 'Jasi'];
- console.log (two);
- A better way to concatenate arrays.
- var First = [0, 1, 2];
- var Second = [3, 4, 5];
- var third = [...First, ... Second];
- console.log (third);
- Spread in object literals
- var Emp1 = {Name:'baljit', Address: 'New York', Salary:'5000'};
- var Emp2 = {Age: 32, Mobile: 98729648};
- var mergedEmp = {...Emp1, …Emp2};
- console.log (mergedEmp);
-
Spread in with Functions
- const numbers = [5, 6, 8, 9, 11, 999];
- Math.max (...numbers)
- Spread in with Array
- const item = ['This', 'is', 'a', 'Java Script'];
- console.log(item)
- console.log (...item)
Summary
In this article, we learned about the Spread operator in JavaScript and how to use it in the program example.