- vừa được xem lúc

Blog#108: 7 ES6 Spread Operator Tricks Should Know

0 0 19

Người đăng: NGUYỄN ANH TUẤN

Theo Viblo Asia

The main goal of this article is to help you improve your English level. I will use Simple English to introduce to you the concepts related to software development. In terms of IT knowledge, it might have been explained better and more clearly on the internet, but remember that the main target of this article is still to LEARN ENGLISH.


Hi, I'm Tuan, a Full-stack Web Developer from Tokyo 😊. Follow my blog to not miss out on useful and interesting articles in the future.

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 and deep 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.

And Finally

As always, I hope you enjoyed this article and learned something new. Thank you and see you in the next articles!

If you liked this article, please give me a like and subscribe to support me. Thank you. 😊


The main goal of this article is to help you improve your English level. I will use Simple English to introduce to you the concepts related to software development. In terms of IT knowledge, it might have been explained better and more clearly on the internet, but remember that the main target of this article is still to LEARN ENGLISH.

Ref

Bình luận

Bài viết tương tự

- vừa được xem lúc

Giới thiệu Typescript - Sự khác nhau giữa Typescript và Javascript

Typescript là gì. TypeScript là một ngôn ngữ giúp cung cấp quy mô lớn hơn so với JavaScript.

0 0 500

- vừa được xem lúc

Bạn đã biết các tips này khi làm việc với chuỗi trong JavaScript chưa ?

Hi xin chào các bạn, tiếp tục chuỗi chủ đề về cái thằng JavaScript này, hôm nay mình sẽ giới thiệu cho các bạn một số thủ thuật hay ho khi làm việc với chuỗi trong JavaScript có thể bạn đã hoặc chưa từng dùng. Cụ thể như nào thì hãy cùng mình tìm hiểu trong bài viết này nhé (go).

0 0 414

- vừa được xem lúc

Một số phương thức với object trong Javascript

Trong Javascript có hỗ trợ các loại dữ liệu cơ bản là giống với hầu hết những ngôn ngữ lập trình khác. Bài viết này mình sẽ giới thiệu về Object và một số phương thức thường dùng với nó.

0 0 136

- vừa được xem lúc

Tìm hiểu về thư viện axios

Giới thiệu. Axios là gì? Axios là một thư viện HTTP Client dựa trên Promise.

0 0 117

- vừa được xem lúc

Imports và Exports trong JavaScript ES6

. Giới thiệu. ES6 cung cấp cho chúng ta import (nhập), export (xuất) các functions, biến từ module này sang module khác và sử dụng nó trong các file khác.

0 0 93

- vừa được xem lúc

Bài toán đọc số thành chữ (phần 2) - Hoàn chỉnh chương trình dưới 100 dòng code

Tiếp tục bài viết còn dang dở ở phần trước Phân tích bài toán đọc số thành chữ (phần 1) - Phân tích đề và những mảnh ghép đầu tiên. Bạn nào chưa đọc thì có thể xem ở link trên trước nhé.

0 0 229