What is a spread operator?
The spread operator in JavaScript is a useful syntax for adding elements to an array, combining arrays into one larger one, spreading an array inside the arguments of a function, and more.
// Concatenating arrays and objects
let arr1 = [1,2,3];
let arr2 = [4,5];
let newArray = [...arr1,...arr2];
console.log(newArray);
// Output: [ 1, 2, 3, 4, 5 ]
// Copying array elements
let arr = ["a","b","c"];
let newArray = [...arr];
console.log(newArray);
// Output: ["a", "b", "c"]
// Expanding arrays
let arr = ["a","b"];
let newArray = [...arr,"c","d"];
console.log(newArray);
// Output: ["a", "b", "c", "d"]
// Merging objects
const userBasic = {
name: "Jen",
age: 22,
};
const userMoreInfo = {
country: "Argentina",
city: "Córdoba",
};
const user = {... userBasic, ... userMoreInfo};
// Output: { name: "Jen", age: 22, country: "Argentina", city: "Córdoba" }
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW