+7

7 ES6 Spread Operator Tricks Should Know

The ES6 Spread Operator is a powerful tool for any JavaScript developer to have in their toolkit. It's a set of three dots (...) that can be used to "spread out" the elements of an iterable object, like an array, map, set, or object.

For example, imagine you have an array of numbers called arr that looks like this: [1, 2, 3, 4, 5]. Instead of looping through the array and console.log each element you can simply use the spread operator to print out the array: console.log(...arr) // 1 2 3 4 5.

Example:

const arr = [ 1, 2, 3, 4, 5 ]

console.log(arr) // [ 1, 2, 3, 4, 5 ]
console.log(...arr) // 1 2 3 4 5

const { name, ...other } = { name: 'tuan', age: 100, luckyNumber: 6 }

console.log(name) // tuan
console.log(other) // { age: 100, luckyNumber: 6 }

But the spread operator can do much more than just that! Here are some other tricks that you can use it for:

1. A better way to use the array's push() method

We all know that the push() method supports passing multiple indeterminate parameters.

const arr = [ 'tuan', 'medium' ]
arr.push(...[ 'JavaScript', 'NodeJs' ])

console.log(arr) // ['tuan', 'medium', 'JavaScript', 'NodeJs']

In this example, we're using the spread operator to spread out the elements of the array [ 'JavaScript', 'NodeJs' ] and use the spreaded out elements as arguments to the push method, which allows us to add multiple elements to the arr in one line instead of having to use push multiple times.

2. Copy a new array (shallow clone)

Copying an array is one of the most convenient functions of the spread operator, but it's worth noting that the spread operator only copies the array itself, not the elements. So if the original array contains objects, any changes made to the copy will also affect the original array as they refer to the same objects.

// This is shallow clone
const originalArray = [1, 2, {a: 1, b: 2}];
const copyArr = [...originalArray];
console.log(copyArr); // [1, 2, {a: 1, b: 2}]

//Modifying the object in the copyArray,
//it will also modify the original array
copyArr[2].a = 3;
console.log(originalArray);  // [1, 2, {a: 3, b: 2}]

If you need to make a true copy of the array, including the objects inside it, you can use a deep copy function such as JSON.parse(JSON.stringify(originalArray)), which can create a deep copy of the original array.

const originalArray = [1, 2, {a: 1, b: 2}];
const copyArr = JSON.parse(JSON.stringify(originalArray));
console.log(copyArr); // [1, 2, {a: 1, b: 2}]

//Modifying the object in the copyArray,
//it will not modify the original array
copyArr[2].a = 3;
console.log(originalArray);  // [1, 2, {a: 1, b: 2}]

It's important to note that JSON.parse(JSON.stringify)) creates a deep copy, but it only works for JSON-compliant data and might not be the best option in terms of performance if you're working with large arrays. It's also worth mentioning that the JSON.parse(JSON.stringify(originalArray)) method will not work if originalArray has a function, Symbol and undefined value

It's also possible to use a library like Lodash or Ramda that have a cloneDeep function which can create a deep copy of an array or an object while also preserving the non JSON data type.

3. Removing duplicate values from the array

Arrays of duplicate values can be removed through the set data structure and the spread operator.

const arr = [ 'tuan', 'tuan', 'medium', 'medium' ]
const uniqueArray = [ ...new Set(arr) ]

console.log(uniqueArray) // ['tuan', 'medium']

4. Connect multiple arrays

Yes, we can use the spread operator to chain multiple arrays to get brand new data.

const arr1 = [ 'tuan', 'medium' ]
const arr2 = [ 'JavaScript', 'NodeJs' ]
const arr = [ ...arr1, ...arr2 ]

console.log(arr) // ['tuan', 'medium', 'JavaScript', 'NodeJs']

5. Convert NodeList to a real array

The spread operator can be used to convert a NodeList, which is a list of DOM elements, into a real array.

// $divs is a NodeList
const $divs = document.querySelectorAll('div')
// $arrayDivs is An Array
const $arrayDivs = [ ...$divs ]
console.log(Array.isArray($divs), Array.isArray($arrayDivs)) // false true

6. Destructuring

The spread operator is often used to destructure arrays and objects, check it out!

Destructure array:

const [ num0, ...others ] = [ 1, 2, 3, 4, 5, 6 ]

console.log(num0) // 1
console.log(others) // [2, 3, 4, 5, 6]

Destructure object:

const obj = { name: 'tuan', age: 100, luckyNumber: 6 }
const { name, ...other } = obj

console.log(name) // tuan
console.log(other) // { age: 100, luckyNumber: 6 }

7. Convert string to array

Isn’t it amazing that a string can be turned into an array like this?

const name = 'tuan'
const nameArray = [ ...name ] // ['t', 'u', 'a', 'n']

Conclusion

The spread operator (...) is a powerful tool that can simplify your code and make it more efficient. It allows you to expand the elements of an iterable object, such as an array, set, map, or object. It can be used for tasks like merging arrays, copying arrays, removing duplicates, destructure arrays and objects, and converting NodeList or string to array.

However, it is important to note that it creates a shallow copy, meaning that any changes made to the copied array will affect the original. Therefore, when necessary, you should use other methods to create a deep copy such as JSON.parse(JSON.stringify(originalArray)) or library like lodash or Ramda.

Mình hy vọng bạn thích bài viết này và học thêm được điều gì đó mới.

Donate mình một ly cafe hoặc 1 cây bút bi để mình có thêm động lực cho ra nhiều bài viết hay và chất lượng hơn trong tương lai nhé. À mà nếu bạn có bất kỳ câu hỏi nào thì đừng ngại comment hoặc liên hệ mình qua: Zalo - 0374226770 hoặc Facebook. Mình xin cảm ơn.

Momo: NGUYỄN ANH TUẤN - 0374226770

TPBank: NGUYỄN ANH TUẤN - 0374226770 (hoặc 01681423001)

image.png


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí