Spread Operator and It’s Uses

|
| By Webner

Introduction

The Spread operator was first introduced in ES6. It allows an expression to be expanded in locations where various elements/variables/arguments are required. In other words, the Spread operator lets users expand an iterable like a string, object or array into its elements while the Rest operator does the inverse by reducing a set of elements into one array.

Syntax of this operator: “…”

Usage:

  • String to Array: This operator simply converts a string to an array of characters.
    Example:

    var str = "hello";
    var chars = [...str];
     
    console.log(chars);
    // output: ['h', 'e',' l',' l', 'o']
    
  • Merging:
    • Merging two arrays:
      var array1 = [‘a’, ‘b’, ‘c’, ‘d’];
      var array2 = [‘e’, ‘f’, ‘g’, ‘h’];
      var array3 = [ ...array1, ...array2];
       
      console.log(array3);
      // output: [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’]
      
    • Merging two objects:
      var obj1 = {name: ‘demo’};
      var obj2 = {email: ‘demo@gmail.com’};
      var obj3 = { ...obj1, ...obj2};
      
      console.log(obj3);
      // output: {name: ‘demo’, email: ‘demo@gmail.com’}
      
  • With object:
    • Assigning object properties to new object:
      var obj1 = {name: ‘demo’};
      var obj2 = [ ...obj1 ];
       
      console.log(obj2);
      // output: {name: ‘demo’}
      
    • Assigning array values to new array:
      var array1 = [‘a’, ‘b’, ‘c’, ‘d’];
      var array2 = [ ...array1 ];
       
      console.log(array2);
      // output: [‘a’, ‘b’, ‘c’, ‘d’]
      
  • Adding New Elements:
    • Adding items to an array:
      var array1 = [‘a’, ‘b’, ‘c’, ‘d’];
      var array2 = [ ...array1, ‘e’, ‘f’ ];
       
      console.log(array2);
      // output: [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
      
    • Adding properties to an object:
      var obj = {name:”demo”};
      obj = {...obj, email:”demo@gmail.com”}
       
      console.log(obj);
      // output: {name: ‘demo’, email: ‘demo@gmail.com’}
      

Leave a Reply

Your email address will not be published. Required fields are marked *