stackoverflow: using es6 spread operator

Using ES6 Spread Operator in JavaScript

ES6 spread operator is a new feature introduced in JavaScript that allows us to expand iterable objects such as arrays, objects, or strings into single elements. It is denoted by three dots (...).

Using Spread Operator with Arrays

With arrays, the spread operator can be used to create a new array by copying the elements of an existing array and adding new elements to it.

const oldArr = [1, 2, 3];
const newArr = [...oldArr, 4, 5];

console.log(newArr); // Output: [1, 2, 3, 4, 5]

The spread operator can also be used to concatenate two or more arrays.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [...arr1, ...arr2];

console.log(arr3); // Output: [1, 2, 3, 4, 5, 6]

Using Spread Operator with Objects

With objects, the spread operator can be used to create a new object by copying the properties of an existing object and adding new properties to it.

const oldObj = { a: 1, b: 2 };
const newObj = { ...oldObj, c: 3 };

console.log(newObj); // Output: { a: 1, b: 2, c: 3 }

The spread operator can also be used to merge two or more objects.

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const obj3 = { ...obj1, ...obj2 };

console.log(obj3); // Output: { a: 1, b: 2, c: 3, d: 4 }

Using Spread Operator with Strings

With strings, the spread operator can be used to convert a string into an array of characters.

const str = "hello";
const arr = [...str];

console.log(arr); // Output: ["h", "e", "l", "l", "o"]

Overall, the spread operator is a useful feature in JavaScript that simplifies the process of copying and merging arrays, objects, and strings.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe