Today I will introduce you some hacking in es6. Specifically as follows.
Start!
Hack 1: Swap variables
We will use Array Destructuring to swap values like the following example:
1 2 3 4 5 6 | let a = 'world', b = 'hello' [a, b] = [b, a] console.log(a) // -> hello console.log(b) // -> world // Nó thật kì diệu @@ |
Hack 2: Async / Await with Destructuring
Array Destructuring is amazing again. It combines with async / await and promises to create a simple and complex flow
1 2 3 4 5 | const [user, account] = await Promise.all([ fetch('/user'), fetch('/account') ]) |
Hack 3: Debugging
We often use debug with console.log and to print out each value. And here it is great with syntax like console.table
1 2 3 4 5 6 7 8 9 | const a = 5, b = 6, c = 7 console.log({ a, b, c }) // kết quả ở đây là 1 đối tượng: // { // a: 5, // b: 6, // c: 7 // } |
Hack 4: One liners
This syntax can be a lot more compact for array operations:
1 2 3 4 5 6 7 | // Tìm kiếm giá trị max trong mảng const max = (arr) => Math.max(...arr); max([123, 321, 32]) // outputs: 321 // Tính tổng các phần tử trong mảng const sum = (arr) => arr.reduce((a, b) => (a + b), 0) sum([1, 2, 3, 4]) // output: 10 |
Hack 5: Array concatenation
Normally we concatenate 2 arrays using the concat operator
And try the following instead of using concat
1 2 3 4 5 6 7 8 9 10 | const one = ['a', 'b', 'c'] const two = ['d', 'e', 'f'] const three = ['g', 'h', 'i'] // Cách cũ #1 const result = one.concat(two, three) // Cách cũ #2 const result = [].concat(one, two, three) // Mới nè ! const result = [...one, ...two, ...three] |
Simple is not it!
Hack: 6 Cloning
For ordinary arrays or objects, we clone them many ways but I found no easy way like this:
1 2 3 | const obj = { ...oldObj } // clone đối tượng const arr = [ ...oldArr ] //clone array |
Quick and light.
Hack 7: Named parameters
Create functions and call functions more readable with destructuring:
1 2 3 4 5 6 7 8 9 10 11 | const getStuffNotBad = (id, force, verbose) => { làm cái gì đó ... } const getStuffAwesome = ({ id, name, force, verbose }) => { làm cái gì đó ... } // Bất cứ nơi đâu trong code ... K hiểu lắm true, true là gì? getStuffNotBad(150, true, true) // Bất cứ nơi đâu trong code... Nó thực sự tuyệt vời -> I ❤ JS!!! getStuffAwesome({ id: 150, force: true, verbose: true }) |
As an example we see the way below it describes more specifically and more explicitly the variables passed to the function instead of the above.
Great!
Source: https://medium.com/dailyjs/7-hacks-for-es6-developers-4e24ff425d0b