How to Use the Spread Operator in Modern JavaScript

The JavaScript spread operator (...) allows us to quickly copy all or part of an existing array or object into another array or object. Spread operator can be used in many cases, like when we want to expand, copy,concat, with a math object.

We can merge two or more arrays by using the spread operator.

 

        
 let array1 = [1,2,3];
 let array2 = [4,5];
 newarray = [...array1,...array2];
 console.log(newarray);             
         
// Output : [ 1, 2, 3, 4, 5 ]
        
    

Copy

we can copy one array to another without using spread operators.  

 

        
let array1 = ['a','b','c'];
let array2 = array1;

array2.push('d'); 
console.log(array2);                
console.log(array1);   

// Output : [ 'a', 'b', 'c', 'd' ]
// Output : [ 'a', 'b', 'c', 'd' ]
        
    

In the above code we can clearly see that when we tried to insert an element inside the array, the original array is also altered which we didn’t intend and is not recommended.

we can copy one array to another using spread operators

        
let array1 = ['a','b','c'];
let array2 = [...array1];
array2.push('d');                             //inserting an element at the end of arr2
console.log(array2);     
console.log(array1);

// Output : ['a', 'b', 'c', 'd']
// Output : ['a', 'b', 'c']
        
    

By using the spread operator we made sure that the original array is not affected whenever we alter the new array.

Expand 

We can expand array values using spread operators. 

 

        
let array1 = ['a','b'];
let array2 = [...array1,'c','d'];
console.log(array2);

// Output : [ 'a', 'b', 'c', 'd' ]
        
    
Posted in

Ankit Patel

Leave a Comment

Your email address will not be published.

Scroll to Top