Clean code with ES6

You should always be as expressive as possible with your code. That usually means you will sometimes sacrifice wordiness with brevity. But sometimes you can get have the best of both worlds. Luckily, ES6 gives you a lot of tools to do just that.

Object destructure func arguments

Now we're getting a little fancy. But it's another great way to shorten code.

const nestedSubarrays = [[1,2], [3,4]]
  for (let [i, j] of nestedSubarrays) {
    console.log(i);
    console.log(j)
  }

Object destructuring can get really really fancy.

const nestedSubarrays = [[1,2], [3,4], [5, 5], [6, 3]]
  const sortedBySecondEl = nestedSubarrays.sort(([a1, b1], [a2, b2]) => {
    return b1 - b2
  })

Arrow functions can be one-liners

The beauty of compact and verbose code. Note that one-liners are denoted using parenthesis, not curly braces. The parenthesis allow implicit return, as opposed to JavaScripts normal explicit return

const arrowFunc = (text) => setTimeout(() => console.log(text), 100))
//or, same thing, but less on a single line:
const arrowFunc = (text) => (
  setTimeout(() => console.log(text), 100)
)

const normalFunction = function(text) {
  setTimeout(function() => {
    console.log(text)
  }, 1000)
}

1 or 3 lines vs 5? Yes please. Youll find this helping you even more in the future with more complex functions when it comes to readable and concise code.

Object destructure shorthand assignment

A basic example. I love and use this all the time.

  const sampleObject = {
  dog: 'Sam',
  cat: 'Snow',
  guineaPig: 'Chub-Chub' //RIP 1998-2002
}

//ES6 object literal shorthand assignment
const { dog, cat, guineaPig } = sampleObject

//Closest ES5 equivalent
var dog = sampleObject.dog, cat = sampleObject.cat, guineaPig = sampleObject.guineaPig

I prefer the ES6 one-liner a lot more than the ES5 equivalent. But this is an unfair comparison, because nobody writes code like that in ES5. This leads me to my point previous point. Clean code in ES6 requires you to approach code from a different prespective.

Comments

Popular posts from this blog

Contrasting var and ES6s new declarations: let and const

Modularity vs. Abstraction. Which is More Important?

Unit testable components pt.3: Testing components