ES6 spread operator

share link

by vsasikalabe dot icon Updated: Mar 16, 2023

technology logo
technology logo

Guide Kit Guide Kit  

In the ES6 standard of JavaScript, Spread Operator is a straightforward and powerful feature. It is used to write more excellent and shorter code. The JavaScript spread operator is identified by three dots (…). The spread operator helps the objects to expand into individual elements. We can use it in the loop for Iterable objects (for ex., Array, Map, Set, etc.). The spread operator is also used to copy all elements from the existing array or object into another array or object. 


Spread syntax is similar to rest syntax. But The main difference between rest and spread is that the rest operator puts the rest of some values supplied by the user into a JavaScript array. But the spread syntax expands iterable objects into individual elements. When you need to include all elements from an object or array in a new array (object) or should be applied one-by-one in a function call's arguments, list the spread operator used. Three places use the spread syntax: 

  • Function arguments list- (myFunction(a, ...iterableObj, b)) 
  • Array literals - ([1, ...iterableObj, '2', 'three', 4]) 
  • Object literals - ({ ...obj, key: 'value' }) 

The spread operator is also used in combination with destructuring. 


Here is an example of how to do the ES6 Spread operator: 

Preview of the output that you will get on running this code from your IDE.

Code

Instructions

Follow the steps carefully to get the output easily.

  1. Download and Install VS Code on your Computer.
  2. Open the VS Code and install Javascript ES6 Code Snippet and Code Runner from Extensions.
  3. Open the new file and save it as example.js (functions.js)
  4. Copy the code using the "Copy" button above, and paste it into your Javascript file. ( Run the code as in the preview )
  5. Run the code using (ctr+alt+N) Run button.


I hope you found this useful. I have added version information in the following sections.


I found this code snippet by searching for ' ES6 spread operator output' in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created in VS Code 1.73.1 version.
  2. JavaScript (ES6) code snippets v1.8.0
  3. Code Runner v0.12.0


Using this solution, we are able to do ES6 spread operator with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to do the ES6 spread operator.

Support

  1. For any support on kandi solution kits, please use the chat
  2. For further learning resources, visit the Open Weaver Community learning page