DEV Community

loading...

What is the spread operator in javascript?

Code_Jedi
Javascript, Node.js, Python, PHP, React and Vue. Coding since 2017
・1 min read

The spread operator in JavaScript is useful for adding elements to an array, combining arrays and more!

Here's an example:

let arr1 = [1,2,3]; 
let arr2 = [4,5]; 
let arr3 = [...arr1,...arr2]; 
console.log(arr3);
// Output: [ 1, 2, 3, 4, 5 ] 
Enter fullscreen mode Exit fullscreen mode

As you can see the spread operator(represented as "...") was able to combine "arr1" and "arr2" into "arr3".


The spread operator can also expand arrays:

let arr = ["a","b"]; 
let arr2 = [...arr,"c","d"]; 
console.log(arr2); 
// Output: ["a", "b", "c", "d"]
Enter fullscreen mode Exit fullscreen mode

As you can see, the spread operator here was able to add elements "c" and "d" to "arr", thus creating a bigger array.


But that's not all!

The spread operator can also merge objects:

const Person = { 
    name: "Bob", 
    age: 45,
}; 
const ExtraInfo = { 
    country: "Belgium", 
    city: "Brussels", 
}; 
const user = {... Person, ... ExtraInfo};
// Output: {  name: "Bob",  age: 45, country: "Belgium", city: "Brussels" }
Enter fullscreen mode Exit fullscreen mode

There it is, the javascript spread operator.


Get the hottest programming stuff of the week in your inbox every Friday via my newsletter!

...

Byeeeee👋

Discussion (1)

Collapse
hugekontrast profile image
Ashish Khare😎

Thanks for sharing!