7 Hacks for ES6 Developers

Hack #1 swaps elements

Use array deconstruction to achieve value interchange

let a = 'world', b = 'hello'
[a, b] = [b, a]
console.log(a) // -> hello
console.log(b) // -> worldCopy the code

Hack # 2 debugging

We often use console.log() for debugging, so it doesn’t hurt to try console.table().

const a = 5, b = 6, c = 7
console.log({ a, b, c });
console.table({a, b, c, m: {name: 'xixi', age: 27}});Copy the code

Hack #3 Single statement

In ES6, manipulating arrays will be much more compact

Const Max = (arr) => math.max (... arr); max([123, 321, 32]) // outputs: Const sum = (arr) => arr.reduce((a, b) => (a + b), 0) sum([1, 2, 3, 4]) // output: 10Copy the code

Hack #4 Array splicing

The expansion operator can take the place of concat

const one = ['a', 'b', 'c']
const two = ['d', 'e', 'f']
const three = ['g', 'h', 'i']

const result = [...one, ...two, ...three]Copy the code

Hack #5 Make copies

We can easily implement shallow copies of arrays and objects

const obj = { ... oldObj } const arr = [ ...oldArr ]Copy the code

Hack #6 Named parameters 👍👍👍

Destructuring makes function declarations and function calls more readable

Const getStuffNotBad = (id, force, verbose) => {... Do stuff} // When we call the function, we'll see tomorrow. Const getStuffAwesome = ({id, name, force, const getStuffAwesome = ({id, name, force, const getStuffAwesome = ({id, name, force, const getStuffNotBad, const getStuffAwesome = ({id, name, force, const getStuffAwesome, const getStuffNotBad, const getStuffAwesome = ({id, name, force, const getStuffAwesome); verbose}) => { ... GetStuffAwesome ({id: 150, force: true, verbose: true})Copy the code

Hack #7 Async/Await with array deconstruction

Array deconstruction is awesome! Combining promise.all with deconstruction and await makes the code much cleaner

const [user, account] = await Promise.all([
  fetch('/user'),
  fetch('/account')
])Copy the code

Course recommended

Thoroughly master JS asynchronous processing Promise and async-await