Spread Operator in javascript

Hey developers! If you are eager to learn various operators and syntax in JavaScript, then give this article a read. In this article, we are going to see what is spread operator in JavaScript is and how to apply it.  

The spread operator comes with the ES6 bundle and brings tons of convenience for us developers. Essentially, a spread operator literally spreads out the list of objects. Let’s have a look at how exactly it is used.  

Example 1: Basic Use of Spread Operator in JavaScript

				
					list_number = [1, 2, 3, 4, 5] 
console.log( ...list_number ) 

// OUTPUT: 1 2 3 4 5 
				
			

Example 2: Combine Multiple Lists Using Spread Operator

				
					list_number = [1, 2, 3, 4, 5] 
list_alpha = ['apple', 'banana', 'cat', 'dog', 'elephant'] 
console.log( [ ...list_number, ... list_alpha ] ) 

// OUTPUT: [1, 2, 3, 4, 5, 'apple', 'banana', 'cat', 'dog', 'elephant'] 
				
			

Example 3: Inserting 1 list into Another Using Spread Operator

				
					list_number = [1, 2, 3, 4, 5] 
list_alpha = ['apple', 'banana', ...list_number, 'cat', 'dog', 'elephant'] 
console.log( list_alpha ) 

// OUTPUT: apple banana 1 2 3 4 5 cat dog elephant 
				
			

Example 4: Passing into Functions Using Spread Operator

				
					list_number = [1, 2, 3, 4, 5] 
console.log( Math.max(... list_number) ) 

// OUTPUT: 5 
				
			

Example 5: Combine Multiple JSON Objects Using Spread Operator

				
					const obj1 = { 
    "name": "Daniyal Akbar", 
    "age": 01 
} 
  
const obj2 = { 
    "gender": "male", 
    "height": 1.11 
} 
  
console.log( 
    {...obj1, ...obj2} 
) 

// OUTPUT: { name: 'Daniyal Akbar', age: 1, gender: 'male', height: 1.11 } 
				
			

 

 

And that’s a wrap! 

Hope you guys enjoyed this article and learned exactly what is spread operator in JavaScript and how it works. For more of these topics, please like this article and comment below.  

Have a great one!