DEV Community

Cover image for Write Minimal ES6 Code
Mursal Furqan Kumbhar
Mursal Furqan Kumbhar

Posted on

Write Minimal ES6 Code

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
Enter fullscreen mode Exit fullscreen mode
const age = !!input.value //new
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode
//new
const addId = (user, id) => {
     user.id = id ?? "Unknown"
     return user
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode
//new
const createUser = (
     name = "Unknown",
     email
) => {
     const user = { email, name }
     // create user
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
//new
const hasValidPostcode = u => u?.address?.postcode?.valid
Enter fullscreen mode Exit fullscreen mode

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
     )
}
Enter fullscreen mode Exit fullscreen mode
//new
const save = ({name, email, dob}) => {
     saveData(name, email, dob)
}
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode
//new
const data = [
     ["axios", "recharts"],
     ["flocked", "flick"]
]

const [plugins, apps] = data
Enter fullscreen mode Exit fullscreen mode

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
)
Enter fullscreen mode Exit fullscreen mode
//new
const details = {name: "Man Utd"}
const stats = {games: 7, points: 21}

const team = {
     ...details,
     ...stats
}
Enter fullscreen mode Exit fullscreen mode

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))
}
Enter fullscreen mode Exit fullscreen mode
//new
const array = []
const fillArray = items => {
     for (let i of items) {
          array.push(i)
     }
}
Enter fullscreen mode Exit fullscreen mode

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.

Happy Coding 👨‍💻

Top comments (14)

Collapse
 
moopet profile image
Ben Sinclair

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 the for clause, but it's actually scoped to the enclosed block so defining it as const is usually the safe move.

Collapse
 
dagnelies profile image
Arnaud Dagnelies

From my experience, the usage of !! is much more common than the explicit Boolean(...) 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.

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

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 for Number (or parseInt, parseFloat, etc. depending on use case) vs +... I want to convert to a number, not make the variable positive.

Collapse
 
sapegin profile image
Artem Sapegin

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.

Collapse
 
lionelrowe profile image
lionel-rowe

Yeah, Airbnb style guide is trash. It also recommends const fn = function longAssDescriptiveName () {} over function normalFunctionName() {} 🤢

Collapse
 
lexlohr profile image
Alex Lohr • Edited

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

Collapse
 
efpage profile image
Eckehard

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.

Collapse
 
klaymant profile image
Clément

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.

Collapse
 
plxel profile image
Aleksei Mikhailov

About #1, !! it is just double logical operator, it exists from first version of JS, not related to ES6 at all

Collapse
 
artydev profile image
artydev

Thank you

Collapse
 
ebcefeti profile image
E. B. Cefeti

I'm not sure what "minimal" is supposed to mean here?

Collapse
 
imashwani profile image
Ashwani Singh

informative content. Good work!

Collapse
 
nahidulislam profile image
Nahidul Fahim

Very informative. Thank you for the post.

Collapse
 
anthony_alejo_04ce7c390cf profile image
Anthony Alejo

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.