Blog#108: 7 ES6 Spread Operator Tricks Should Know

image.png

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 (with deep copy)

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.

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.

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

NGUYỄN ANH TUẤN

Xin chào, mình là Tuấn, một kỹ sư phần mềm đang làm việc tại Tokyo. Đây là blog cá nhân nơi mình chia sẻ kiến thức và kinh nghiệm trong quá trình phát triển bản thân. Hy vọng blog sẽ là nguồn cảm hứng và động lực cho các bạn. Hãy cùng mình học hỏi và trưởng thành mỗi ngày nhé!

Đăng nhận xét

Mới hơn Cũ hơn