Spread Operator in JavaScript

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
  1. var variablename = [...value]; 
Examples are given below.
  1. const nambers = [1, 2, 3 ,4 ,5 ,6 ,7 ,8 ,9 ,10];
    console.log (...nambers);
     
    image1
  2. Spread in function calls
    1. function Subtract (x, y, z) {  
    2.              return x * y * z;  
    3. }  
    4. const Subnumbers = [5,6,7,8];  
    5. console.log (Subtract (...Subnumbers)); 
  3. image2
     
  4. Spread in array literals
    1. var one = ['Ravi''Vicky'];   
    2. var two = ['mohit', ...one, 'and''Jasi'];   
    3. console.log (two); 
    image3
     
  5. A better way to concatenate arrays.
    1. var First = [0, 1, 2];  
    2. var Second = [3, 4, 5];  
    3. var third = [...First, ... Second];  
    4. console.log (third);  
    image4
  6. Spread in object literals
    1. var Emp1 = {Name:'baljit', Address: 'New York', Salary:'5000'};  
    2. var Emp2 = {Age: 32, Mobile: 98729648};  
    3. var mergedEmp = {...Emp1, …Emp2};  
    4. console.log (mergedEmp); 
    image5
     
  7. Spread in with Functions
    1. const numbers = [5, 6, 8, 9, 11, 999];  
    2. Math.max (...numbers) 
    image6
  8. Spread in with Array
    1. const item = ['This''is''a''Java Script'];  
    2. console.log(item)   
    3. console.log (...item) 
    image7

Summary

 
In this article, we learned about the Spread operator in JavaScript and how to use it in the program example.


Similar Articles