JavaScript | Spread Operator

Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in variable array where there is more than 1 values are expected. Syntax of Spread operator is same as Rest operator but it works completely opposite of it.
Syntax:

 var variablename1 = [...value]; 

In the above syntax, … is spread operator which will target all values in particular variable.

JavaScript code to show the working of this operator:

Code #1:
Copying value from one array to another. In this code, Spread Operator basically run a inbuilt for loop like structure for user so that all values can be copied to another variable

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
  
   // value for 1st variable
   var val = [ 3, 4 ];
     
   // both values of 1st variable will be
   // copied into 'nor' variable
   var nor = [ 1, 2, ...val, 5, 6 ];
   document.write(nor);
     
</script>                    

chevron_right


Output:

 1, 2, 3, 4, 5, 6 

Code #2:
Performing operation using spread operator:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
  
   var arr = [ 2, 5, 7, 8, 0 ];
     
   // whole array is passed to math
   // function using spread operator
   var max = Math.max(...arr);
   document.write(max);
     
</script>

chevron_right


Output:

8


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.