Random UTF-8 characters

Home

16 Apr 2016 in javascriptes6eslint

Linting in ES6

I've talked about linting before and it's benefits. After updating all our code to ES6 we had to update our linting rules.

We are using the AirBnB style guide, which has also been updated with some nice ES6 defaults. There was a ton of updates to make, but it's worth it to have clean consistent code.

Here were our most common linting errors and why they should be corrected.

Template Literals

Template literals are a cleaner way to combine strings. You should never be writing 'foo' + x in ES6. Templates make string concatenation a breeze `foo${x}` . Our linting rules enforce us to use literals when concatenating strings, but also for us to not lazily use string templates when there is not any concatenation taking place. `Some string` is an error!

Object Literal Shorthand

There is a lot of enhancements in ES6 to let you write shorter and more concise code. This includes object literal shorthand. How often do you see code that looks like:

const name = 'Some Name';
const title = 'A title';

this.setState({ name: name, title: title});

Shorthand makes this a bit more concise:

const name = 'Some Name';
const title = 'A title';

this.setState({ name, title});

Arrow Functions

One of the best additions to ES6 is arrow functions. Inheriting the local this of the code surrounding them make arrow functions very useful. Enforcing that we use arrow functions cleans up a ton of code.

The old: let foo = function() { return this.bar; }.bind(this); Becomes: let foo = () => this.bar;

Other changes

We did have a multitude of other linting changes. The rest however are cosmetic. We turned on comma dangle, added spacing around { object } brackets and enforced a line length. These changes are purely visual and just help our code look consistent.

If you are not using a linter on your Javascript code I suggest you start now. The longer you wait the more refactoring you'll have to do!