Javascript Spread Operator (...)

Javascript Spread Operator (...)

The spread operator is an additional feature in JavaScript ES6 version. Just as the name implies, spread means to extend, expand or stretch something.

The spread operator which is represented by ellipsis (...) is used to expand, spread or copy existing code (array or object) into a new one.

Example:

const arr1 = [1, 2, 3];
console.log(...arr1)

//Output: 1 2 3

You can use the spread operator to copy or combine arrays. Example:

const arr1 = [2, 4, 6];
const arr2 = [8, 10, 12];
const arr3 = [...arr1, ...arr2];
console.log(arr3)

//Output: [2, 4, 6, 8, 10, 12]

You can also spread objects. Example:

const obj1 = {
    firstName: 'John'
};
const obj2 = {
    lastName: ' Carter'
};
let obj3 = {...obj1, ...obj2}
console.log(obj3)

//Output: {firstName: 'John', lastName: 'Carter'}

The spread operator can also be used to destructure an array. Example:

const numbers = [1, 2, 3, 4, 5, 6];
const [one, two, ...others] = numbers;

console.log(numbers)

//Output: [1, 2, 3, 4, 5, 6]

JavaScript spread operator makes our code look simple and readable.

If you find this useful, subscribe for new articles.