JavaScript ES6 provides a new operator called spread operator that consists of three dots (...
).
Though conceptually the spread operator is always used to “expand” an array or iterable object, the exact usage and behavior varies a bit based on the context.
In this post, we will look at JavaScript’s spread operator, and the many different ways it can be used.
What is the Spread Operator in JavaScript?
Spread operator (...
) allows you to expand an array or object or any other iterables into its individual elements.
For example:
const odd = [1,3,5]; const combined = [2,4,6, ...odd]; console.log(combined); //[ 2, 4, 6, 1, 3, 5 ]
In this example, the three dots (...
) located in front of the odd array is the spread operator.
The spread operator (...
) here, unpacks the elements of the odd array. In other words, when we use the spread operator we get the values independently.
Kindly note that spread operator (...
) is effective only when used within array literals, function calls, or initialized properties objects.
With that said, let’s dig in to the various ways to use the spread operator!
Copy (Clone) Array Using Spread Operator
You can use the spread operator to copy the items into a single array.
For example,
const fruits = ['Apple', 'Banana', 'Pear', 'Watermelon']; const moreFruits = [...fruits]; console.log(moreFruits); //[ 'Apple', 'Banana', 'Pear', 'Watermelon' ]
Combining (Merge) Arrays Using Spread Operator
As we saw in the last example, arrays can be easily added together with the spread operator.
const firstArray = [1, 2, 3]; const secondArray = [4, 5, 6]; const combinedArray = [...firstArray, ...secondArray] console.log(...combinedArray) // 1 2 3 4 5 6
Using Spread Operator With Math Object
Math.min
and Math.max
functions can be made easier with the spread operator:
For example,
const numbers = [37, -17, 7, 0] console.log(Math.min(numbers)) // NaN console.log(Math.min(...numbers)) // -17 console.log(Math.max(...numbers)) // 37
Using Spread Operator With Strings
JavaScript allows you to use spread operator also with strings.
When you use spread on a string, the result will be the same as if you would use split()
method.
In other words, spread operator will convert the string into an array. You will get that string in the form of individual characters, that is words, digits and whitespace.
// Create some text const text = 'Sunny day.' // Use spread to convert the string into an array const processedText = [...text] // Log the content console.log(processedText) /*Output: ------------------- [ 'S', 'u', 'n', 'n', 'y', ' ', 'd', 'a', 'y', '.' ] -----------------------------*/
Spread Operator and Object Literals
When you want to use spread operator with object literals the syntax is the same.
You will use those three dots, but now followed by the name of the object whose content you want to access. The result you will get will be the content, only without the surrounding curly braces.
// Create object literal const myObj = { firstName: 'Sunil', lastName: 'Pradhan' } // Use spread operator to access content of "myObj" variable // Note: the {} around ...myObj are to avoid TypeError // console.log(...myObj) would not work console.log({ ...myObj }) /*Output: ------------------- { firstName: 'Sunil', lastName: 'Pradhan' } -----------------------------*/
Merging Object Literals With Spread Operator
Merging object literals with spread operator works just like with arrays.
The only difference in syntax is that you have to use curly brackets instead of square brackets to wrap everything.
The rest is the same and the result is a new object literal with merged content of the object literals you specified.
// Create first object const myObjOne = { title: 'Catalyst', author: 'Venkatesan Chandramouli', } // Create second object const myObjTwo = { publicationDate: '2018', format: 'Paperback' } // Create third object const myObjThree = { language: 'English', genre: 'Self help book' } // Use spread operator to merge "myObjOne", "myObjTwo" and "myObjThree" const myMergedObj = { ...myObjOne, ...myObjTwo, ...myObjThree } // Log the content of "myMergedObj" console.log(myMergedObj) /*Output: ------------------- { title: 'Catalyst', author: 'Venkatesan Chandramouli', publicationDate: '2018', format: 'Paperback', language: 'English', genre: 'Self help book' } -----------------------------*/
Inserting Data With Spread Operator
We discussed how to use spread operator to access content of arrays and object literals.
This is not all you can do. You can also use spread operator to data. You can take content of one iterable and insert it inside another iterable.
For example, let’s say you have two arrays with some content. Spread operator allows you to insert the content of one anywhere inside the second.
// Create first array const myArrayOne = ['C', 'C++', 'Java'] // Create second array with some content // plus all the content from "myArrayOne" const myArrayTwo = ['JavaScript', 'Python', 'PHP', ...myArrayOne, 'Assembly'] // Log the content of "myArrayTwo" console.log(myArrayTwo) /*Output: ------------------- [ 'JavaScript', 'Python', 'PHP', 'C', 'C++', 'Java', 'Assembly' ] -----------------------------*/
You can do this also with object literals, insert content from one anywhere inside another. Or, you can insert object literal into an array or vice versa.
// Create first object literal const myObjOne = { numOfPages: 74, publisher: 'Penguin' } // Create second object literal with some content // plus all the content from "myObjOne" const myObjTwo = { title: 'Catalyst', author: 'Venkatesan Chandramouli', ... myObjOne, // insert the content of "myObjOne" language: 'English' } // Log the content of "myObjTwo" console.log(myObjTwo) /*Output: ------------------- { title: 'Catalyst', author: 'Venkatesan Chandramouli', numOfPages: 74, publisher: 'Penguin', language: 'English' } -----------------------------*/
Spread Operator and Function Arguments
When you use spread operator to access content of an iterable, it will return only the content.
It will remove the surrounding square brackets in case of an array or curly brackets in case of an object literal.
This can be handy when you want to call a function that takes some arguments.
Instead of passing each argument one by one, you can pass in an array with all arguments preceded by spread operator.
The result will be the same as if you would pass all arguments one by one.
// Create an array with something // that will be used as arguments const StudentName = ['Sunil', 'Ram', 'Gopal'] // Create a simple function // that will return all arguments one by one function sayNames(name1, name2, name3) { return `Student names you passed are ${name1}, ${name2} and ${name3}.` } // Call sayNames() function using spread operator // to pass in content of "myArgs" as arguments console.log(sayNames(...StudentName)); /*Output: ------------------- Student names you passed are Sunil, Ram and Gopal. -----------------------------*/
The next example is slightly different. Suppose we have a list of 100 people in an array to whom we need to greet.
// For simplicity we are considering only 3 names
let names = ['Sunil', 'Ram', 'Gopal'];
This can be achieved using the spread operator, for this we are creating a greetings function, which uses …names
as a parameter.
Inside the greetings function, we have a for…of loop that iterates through the list of array.
Also Read: JavaScript Loops Explained With Examples
Then it will expand the array into its elements at the place of the function call.
// For simplicity we are considering only 3 names let names = ['Sunil', 'Ram', 'Gopal']; function greetings(...names){ for(let name of names){ console.log(`Hello, ${name}!`); } } console.log(greetings(...names)); /*Output: ------------------- Hello, Sunil! Hello, Ram! Hello, Gopal! -----------------------------*/
Conclusion
The spread operator is a convenient feature added in ES6 to help working with array and objects.
The spread syntax can save a lot of time while programming, and is an important tool to have in your JavaScript toolkit.
Add comment