Javascript Spread Operator

⚡ ALL INFORMATION CLICK HERE 👈🏻👈🏻👈🏻
Javascript Spread Operator
Difficulty Level :
Medium
Last Updated :
03 Jun, 2020
console.log(arr); // [ 1, 2, 3, 4, 5 ]
// spread operator doing the concat job
console.log(arr); // [ 1, 2, 3, 4, 5 ]
// copying without the spread operator
console.log(arr2); // [ 'a', 'b', 'c' ]
console.log(arr); // even affected the original array(arr)
console.log(arr); // [ 'a', 'b', 'c' ]
arr2.push( 'd' ); //inserting an element at the end of arr2
console.log(arr2); // [ 'a', 'b', 'c', 'd' ]
console.log(arr); // [ 'a', 'b', 'c' ]
console.log(arr2); // [ [ 'a', 'b' ], 'c', 'd' ]
console.log(arr2); // [ 'a', 'b', 'c', 'd' ]
console.log(Math.min(1,2,3,-1)); //-1
// min in an array using Math.min()
console.log(Math.min(...arr)); //-1
const mergedUsers = {...user1, ...user2};
What is the meaning of spread operator (...) in Reactjs?
JavaScript Course | Conditional Operator in JavaScript
JavaScript | ‘===’ vs ‘==’Comparison Operator
Difference between == and === operator in JavaScript
Arrow operator in ES6 of JavaScript
What is the !! (not not) operator in JavaScript?
How to get negative result using modulo operator in JavaScript ?
Difference between != and !== operator in JavaScript
What is JavaScript >>> Operator and How to use it ?
JavaScript Nullish Coalescing Operator
What does +_ operator mean in JavaScript?
JavaScript Unsigned Right Shift Assignment Operator
JavaScript SyntaxError - Missing name after . operator
JavaScript SyntaxError - Applying the 'delete' operator to an unqualified name is deprecated
favorite_border
Like
JavaScript Date toLocaleTimeString() Method
Current difficulty :
Medium
Easy
Normal
Medium
Hard
Expert
Data Structures and Algorithms – Self Paced Course
Ad-Free Experience – GeeksforGeeks Premium
More related articles in JavaScript
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
Company
About Us
Careers
Privacy Policy
Contact Us
Copyright Policy
Learn
Algorithms
Data Structures
Languages
CS
Subjects
Video Tutorials
Practice
Courses
Company-wise
Topic-wise
How to begin?
Contribute
Write an Article
Write Interview
Experience
Internships
Videos
@geeksforgeeks
, Some rights reserved
Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 values are expected. It allows us the privilege to obtain a list of parameters from an array. Syntax of Spread operator is same as Rest parameter but it works completely opposite of it.
In the above syntax, … is spread operator which will target all values in particular variable. When … occurs in function call or alike,its called a spread operator. Spread operator can be used in many cases,like when we want to expand,copy,concat,with math object . Let’s look at each of them one by one:
Note : In order to run the code in this article make use of the console provided by the browser.
The concat() method provided by javascript helps in concatenation of two or more strings(String concat() ) or is used to merge two or more arrays. In case of arrays,this method does not change the existing arrays but instead returns a new array.
link
brightness_4
code
Output:
We can achieve the same output with the help of the spread operator, the code will look something like this:
link
brightness_4
code
Output:
Note : Though we can achieve the same result, but it is not recommended to use the spread in this particular case, as for a large data set it will work slower as when compared to the native concat() method.
In order to copy the content of array to another we can do something like this:
link
brightness_4
code
The above code works fine because we can copy the contents of one array to another, but under the hood, it’s very different as when we mutate new array it will also affect the old array(the one which we copied). See the code below:
link
brightness_4
code
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 intended and is not recommended. We can make use of the spread operator in this case, like this:
link
brightness_4
code
By using the spread operator we made sure that the original array is not affected whenever we alter the new array.
Whenever we want to expand an array into another we do something like this:
link
brightness_4
code
Output:
Even though we get the content on one array inside the other one, but actually it is array inside another array which is definitely what we didn’t want. If we want the content to be inside a single array we can make use of the spread operator.
link
brightness_4
code
The Math object in javascript has different properties that we can make use of to do what we want like finding the minimum from a list of numbers, finding maximum etc. Consider the case that we want to find the minimum from a list of numbers,we will write something like this:
link
brightness_4
code
Output:
Now consider that we have an array instead of a list, this above Math object method won’t work and will return NaN, like:
link
brightness_4
code
Output:
When …arr is used in the function call, it “expands” an iterable object arr into the list of arguments
In order to avoid this NaN output, we make use of spread operator, like:
link
brightness_4
code
Example of spread operator with objects
ES6 has added spread property to object literals in javascript. The spread operator ( … ) with objects is used to create copies of existing objects with new or updated values or to make a copy of an object with more properties. Let’s take at an example of how to use the spread operator on an object,
link
brightness_4
code
Here we are spreading the user1 object. All key-value pairs of the user1 object are copied into the clonedUser object. Let’s look on another example of merging two objects using the spread operator,
link
brightness_4
code
mergedUsers is a copy of user1 and user2 . Actually, every enumerable property on the objects will be copied to mergedUsers object. The spread operator is just a shorthand for the Object.assign() method but, they are some differences between the two.
Writing code in comment?
Please use ide.geeksforgeeks.org ,
generate link and share the link here.
How to Use the Spread Operator (…) in JavaScript | by Dr. Derek... | Medium
JavaScript | Spread Operator - GeeksforGeeks
Spread Operator in JavaScript
The Practical Usages of JavaScript Spread Operator
JavaScript Spread Operator : A Guide | Career Karma
Toggle navigation
Stack Abuse
JavaScript
Python
Java
Jobs
Ireland
Website
A Software Engineer who is passionate about writing programming articles. Founder of CosmoCode.io - Free Coding tutorials
Jobs via
HireRemote.io
Copyright © 2021, Stack Abuse . All Rights Reserved.
In this tutorial, we'll explore one of the powerful features of the ES6 specification of JavaScript - the Spread Operator. Although the syntax is simple, sometimes the implementation is confusing if you do not understand it properly. In this tutorial, we'll demystify those three dots ... of JavaScript that does amazing things with iterables.
There are different usages of the spread operator and each usage target to solve a different problem statement.
We can use the spread operator on iterables like a String or an array and it'll put the contents of the iterable into individual elements.
If we run this code we'll see the following:
You must have noticed that in the second case (with spread operator), the contents of the greet list were expanded and thrown out of the array.
Sometimes, we may feel the need to convert a String into a list of characters. We can use spread operator for this use-case:
If we run this code, we'll be greeted with:
These examples might not convince you of the usefulness this operator offers. In that name, let's take some real-world problems that can be solved with the spread operators.
Let us take advantage of the fact that we can now expand an array using the spread operator. Let's say we have subscriber lists from two different sources and we want to combine both these sources and make a single subscribers list:
If we run the above code, we'll get a single list of iterables. This was made possible as both ...blog1Subscribers and ...blog2Subscribers were spread out and the [] acted as the "receiver", which effectively combined the spread items into a single list of items.
Note: The spread operator needs the receiver to put the expanded value into. If you omit the receiver, it'll throw an error.
We can also use the spread operator inside the Array.push() method to push the contents of one array into another:
If we run this code, we'll see the following output:
In JavaScript every non-primitive entity is an Object , which means that arrays are also objects. You may know that objects are copied as a reference-type:
As expected, the values of the items in the array weren't copied, only the reference to them. We can solve this problem easily with the spread operator:
Running this code produces the following:
As we can see, the arr2 wasn't passed a reference like before, but rather it was populated with the values of arr1 as a whole new object. So even when arr1 changes, arr2 remains the same.
We can also use the spread operator to create a copy of an array and add new elements into it at the same time:
Note: The spread operator works with all iterables, including Objects.
Previously this would have taken an extra line of code to add the new items to the new array.
Similarly we can copy objects by using the spread operator:
As we can see we successfully copied the object o1 into o2 .
This feature has many real-world use-cases. For example, let us say we stored user registration information into an object. We can make a shallow copy of that object and add some more information into the copied object:
We may also need to merge billing and shipping information into one:
If we run this code, we should be greeted with:
One question could be raised here. What if both objects have some of the same properties.
In case of clashing properties, the property of the last object wins. Let us see this in an example:
If you run this code, you should see the following:
As we can see the properties of the second object o2 wins. However, if we put the spread operator first:
We can see that the property from o1 wins, which makes sense since o2 is the last object.
One use case of this feature could be to make default assignments:
Let us say a function takes an argument - a list of marks of top 5 students in a class. We also have a list coming from an external source. Surely, we can avoid passing individual items and instead pass the entire list by using the apply() method:
We can get rid of the confusing undefined argument and make the code cleaner by calling the function directly with the spread operator:
JavaScript has a Math object which contains several methods to operate with a set of data, i.e. a list of data.
Let us say we want to get the maximum value from first three numbers of a list:
What if we want to get the maximum of all numbers in a list? What if the list has n number of items? Surely we wont want mylist[0], mylist[1]... mylist[1000] .
The spread operator provides a cleaner solution:
Note: Given that the spread operator works with both Arrays and Objects, you may sometimes be tempted to mix and match them. Don't do that! For example, the following action will result in an error:
Both the Spread Operator and Rest Parameter share the same syntax i.e. the three magical dots ... . But they behave exactly opposite to each other. As a beginner, sometimes this may be confusing. The bottom-line to understand the behavior is to understand the context in which it is being used.
As we learned, the spread operator expands the contents of an iterable. In contrast, the rest operator collects all the remaining elements into an array.
If we run the above code, we'll be greeted with the following:
As we can see, everytime the remaining elements were collected by the Rest Parameter .
We can also provide distinct variables for some of the elements and make the rest parameter collect the rest of the items. The only condition is that the rest parameter should always be the last parameter of the function:
If we run the above code, we'll see the following:
As we can see the spread operator ... is a really powerful feature of the ES6 specification of JavaScript. We can solve plenty of the real-world problems easily by using this operator. As we learned from the various examples discussed in this article, it lets us write less code and do more.
In this article, we covered the common usages of the Spread Operator . We also discussed the similar-looking, but different, Rest Parameter . Please be aware that there could be dozens of other use-cases depending on the problem.
Get occassional tutorials, guides, and jobs in your inbox. No spam ever. Unsubscribe at any time.
Understand your data better with visualizations!
With over 330+ pages, you'll learn the ins and outs of visualizing data in Python with popular libraries like Matplotlib, Seaborn, Bokeh, and more.
Subscribe to our newsletter! Get occassional tutorials, guides, and reviews in your inbox.
Pussy Masturbate Porn
Mom Caught Masturbating
Razer Deathadder Overwatch
Best Overwatch Porn Compilation
Dj Rhiannon Nasty Bitch

















































