Skip to content
the poor coder

stackoverflow: using es6 spread operator

Poor Man
Published
Reading time
2 min read
On this page

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.

Text
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.

Text
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.

Text
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.

Text
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.

Text
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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC