SoFunction
Updated on 2025-03-06

7 practical tips for sharing ES6

Hack #1 Exchange Elements

Use array deconstruction to achieve value interchange

let a = 'world', b = 'hello'
[a, b] = [b, a]
(a) // -> hello
(b) // -> world

Hack #2 Debugging

We often use () for debugging, and it doesn't matter if we try ().

const a = 5, b = 6, c = 7
({ a, b, c });
({a, b, c, m: {name: 'xixi', age: 27}});

Hack #3 Single Statement

In the ES6 era, the statements that operate arrays will be more compact

// Find the maximum value in the arrayconst max = (arr) => (...arr);
max([123, 321, 32]) // outputs: 321
// Calculate the sum of the arrayconst sum = (arr) => ((a, b) => (a + b), 0)
sum([1, 2, 3, 4]) // output: 10

Hack #4 Array Mapping

The expand operator can replace the status of concat

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

Hack #5 Make a Copy

We can easily implement shallow copies of arrays and objects

const obj = { ...oldObj }
const arr = [ ...oldArr ]

Hack #6 Named Parameters 👍👍👍

Deconstruction makes function declarations and function calls more readable

// Let's try the writing method usedconst getStuffNotBad = (id, force, verbose) => {
 ...do stuff
}
// When we call the function, let’s look at it tomorrow. What is 150 and what is truegetStuffNotBad(150, true, true)
// After reading this article, you can forget anything. I hope you can remember the followingconst getStuffAwesome = ({id, name, force, verbose}) => {
 ...do stuff
}
// PerfectgetStuffAwesome({ id: 150, force: true, verbose: true })

Hack #7 Async/Await combined with array destruction

Array deconstruction is great! Combining with deconstruction and await will make the code more concise

const [user, account] = await ([
 fetch('/user'),
 fetch('/account')
])

Summarize

The above are 7 practical tips for sharing ES6 that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!