In the constantly-changing JavaScript ecosystem, designing simple and efficient code is more important than ever. The release of ES6 introduced a slew of new capabilities that simplify and streamline the way we write JavaScript. This article discusses various new ES6 approaches that can replace older, more verbose patterns, resulting in cleaner and more readable code. From Boolean casting to the powerful spread operator, these strategies increase code readability, efficiency, and maintainability. Let's look at some of the essential techniques that any JavaScript writer should follow to build minimum ES6 code.
1. Boolean Casting
Today's recommended method according to Airbnb's style guide
const age = Boolean(input.value) //old
const age = !!input.value //new
2. Nullish Coalescing
Returns its right-hand side when its left-hand side operand is null or undefined
//old
const addId = (user, id) => {
user.id =
id !== null && id !== undefined
? id
: "Unknown"
return user
}
//new
const addId = (user, id) => {
user.id = id ?? "Unknown"
return user
}
3. Default Parameters
Description: Function Parameters default to undefined, so it's useful to set a value for this eventuality.
//old
const createUser = (name, email) => {
const user = {
email,
name: name ?? "Unknown",
}
// create user
}
//new
const createUser = (
name = "Unknown",
email
) => {
const user = { email, name }
// create user
}
4. Optional Chaining
Description: Allows you to read the value of a deeply nested property without checking if it's a valid chain.
//old
const hasValidPostcode = u =>
u &&
u.address &&
u.address.postcode &&
u.address.postcode.valid
//new
const hasValidPostcode = u => u?.address?.postcode?.valid
5. Destructuring Objects
Description: Write less code by unpacking properties from objects into distinct variables.
//old
const save = params => {
saveData(
params.name,
params.email,
params.dob
)
}
//new
const save = ({name, email, dob}) => {
saveData(name, email, dob)
}
6. Destructuring Arrays
Description: Write less code by unpacking values from arrays into distinct variables.
//old
const data = [
["axios", "recharts"],
["flocked", "flick"]
]
const plugins = data[0], apps = data[1]
//new
const data = [
["axios", "recharts"],
["flocked", "flick"]
]
const [plugins, apps] = data
7. Spread Operator
Description: Merge two objects into one using this cool syntax, also very clean when coding objects.
//old
const details = {name: "Man Utd"}
const stats = {games: 7, points: 21}
const team = Object.assign(
{},
details,
stats
)
//new
const details = {name: "Man Utd"}
const stats = {games: 7, points: 21}
const team = {
...details,
...stats
}
8. For(of)
Description: Arguably the same amount of code required but for(of) is known to be 24% faster than forEach.
//old
const array = []
const fillArray = items => {
items.forEach(i => array.push(i))
}
//new
const array = []
const fillArray = items => {
for (let i of items) {
array.push(i)
}
}
Conclusion
To summarize, using ES6 features may significantly simplify your JavaScript code, making it more brief, legible, and efficient. Integrating these current methods will result in cleaner and more maintainable code, improving both development and performance. Implement these approaches to improve your code standards and simplify your tasks.
Top comments (15)
I strongly disagree with point 1. It looks way too much like optimising for code size rather than clarity, and it's completely pointless. People who care about saving 7 bytes are going to be shocked at what happens when they run their code through a minimiser, which is what's going to happen during the build, and then those people are going to be shocked at what happens when their script is gzipped and maybe even SPDYd up during transmission over https.
In point 8, I think you should default to using
const
for the variable. It might seem like it's being re-assigned in thefor
clause, but it's actually scoped to the enclosed block so defining it asconst
is usually the safe move.From my experience, the usage of
!!
is much more common than the explicitBoolean(...)
cast. Actually, I have never even seen it in practice yet. So from my POV,!!
feels familiar and straightforward while the cast feels ...hmm ...very exotic.Really? I use explicit casts all the time as they seem so much clearer in intent. The explicit meaning of
!!
is "not-not", rather than "convert to boolean". Similarly forNumber
(orparseInt
,parseFloat
, etc. depending on use case) vs+
... I want to convert to a number, not make the variable positive.I have found multiple bugs in react applications because of that !!
Totally agree ā shorter isn't always better, and we shouldn't optimize for code brevity but for code clarity. I've collected many more similar examples, though
!!
is probably the most harmless and commonly used of all.Yeah, Airbnb style guide is trash. It also recommends
const fn = function longAssDescriptiveName () {}
overfunction normalFunctionName() {}
š¤¢#1 If you don't use terser or another JS minification engine, go ahead, otherwise it makes no difference whatsoever.
#5/6/7 Be aware that proxies and getters will only be called once in destructuring and spreading. If those are used e.g. to provide subscription for reactive behavior (e.g. in Solid.js), this will break your code.
#8 never use forEach like this to copy an array. Use
const array = [...items]
for a shallow copy to be even faster.Otherwise, avoid premature optimisations.
Why age from example 1 is a boolean?
Despite its conciseness I'm not a big fan of the "!!". It's not very explicit about what it does.
Does "less is more" mantra is that relevant in programmation? Do we have to write minimal code no matter the situation? I don't think so.
This type of "optimization" is overestimated in most cases. Javascript does a very good job optimizing execution (with some very special exceptions like for/in), and the effort to save some bytes often does not really pay back. On the long run, good readability and a clear structure shouldn't be sacrificed just to minimize the code size.
About #1,
!!
it is just double logical operator, it exists from first version of JS, not related to ES6 at allThank you
informative content. Good work!
Very informative. Thank you for the post.
I'm not sure what "minimal" is supposed to mean here?
Trying to get better with JS anyone have any tips or recommendations
Some comments may only be visible to logged-in visitors. Sign in to view all comments.