12 Rules for Professional JavaScript in 2016

Cory House
7 min readSep 24, 2015

Disclaimer: I speak in absolutes below for brevity. Yes, nearly every “rule” in programming has exceptions.

JavaScript is hard. It moves so fast that it’s often unclear whether you’re “doing it wrong” at any given moment. Some days it feels like the bad parts outweigh the good parts.

Well, that’s disturbing.

Yet there’s no point in fighting it. JavaScript is eating the world. So we might as well do it right.

Here’s my take.

1. JS Belongs in a .js File

“C’mon, it’s only a few lines…” Yes, I mean nearly all*. Why? Because it aids readability, enforces structure, and saves bandwidth. Inline JavaScript must be downloaded every time the page is loaded. In contrast, separate .js files are cached. As you’ll see, this rule helps support a long list of other rules below. That’s why it’s rule #1.

2. JS Code Should be Static

I’ve seen many creative hacks for making JavaScript dynamic. People use server-side languages like C#, Ruby, or Java to write dynamic JavaScript in a string. Don’t do that. You lose code coloring, syntax highlighting, and intellisense support. And remember, JavaScript belongs in a .js file (see rule #1).

Instead, use JSON to introduce dynamic behavior. I call this the JavaScript Configuration Object Pattern. Here’s how: inject JSON into the head of your application and utilize that data to fork logic as needed. You might be thinking “Hey, this contradicts rule 1!” I view JSON as data, not code, so I make an exception here in order to support static, separate JavaScript files.

StackOverflow uses this pattern. As does Google. So you’re in good company. Just view their source:

Note the chunk of JSON. This is simply a server-side class that’s been serialized to JSON and injected on the page.

As you can see, StackOverflow is injecting personal settings like isNoticesTabEnabled. This simple snippet of JSON provides the necessary data for providing custom behaviors while using static JavaScript code files. To make this happen, serialize a server-side class into JSON and place the result in <head>. Then you can reference this data structure as needed in your static JavaScript code, knowing it will be available because it’s injected in the <head>.

3. JS Should be Minified

Minifying reduces file sizes, which speeds page loads. Remember, performance is a feature. And of course, to minify, you need to place JavaScript in a separate file (Again, rule #1). Minification was once a hassle. Today, it’s automated and simple. There’s a dozen ways to get it done, but Gulp with gulp-uglify is a low-friction and automated way to get rolling.

4. JS Should Be Linted Real-time

Linting enforces style guidelines, finds typos, and helps avoid errors. There’s a variety of linters out there, but I suggest ESLint. You can run it via Gulp with gulp-eslint. Gulp can watch all your JS files and run the linter everytime you hit save. Oh, and again, you need your JS in a separate .js file to lint it. Starting to see why I made “JS should be in a separate file” rule #1?

5. JS Should Have Automated Tests

We understood testing was important on the server years ago. But it’s been largely ignored in JavaScript until fairly recently. Today’s typical JavaScript application has more surface area than you can practically test regularly by hand. With JavaScript handling so much logic, it’s critical to have automated tests.

You can do automated integration testing via tools like Selenium. However, integration tests are often brittle, so I suggest focusing on automated unit testing. There’s a variety of options for automated unit testing. I suggest Jasmine if you’re new to JavaScript testing and Mocha with Chai if you want the ultimate configurability.

6. JS Should Be Encapsulated

We learned the risks of global variables years ago. Thankfully, there are many ways to encapsulate JavaScript these days:

Bottom line, ES6 Modules are the future. The great news is, although they’re not yet supported in browsers, you can use ES6 modules today if you transpile via Babel (and as you’ll see below, you should).

If you don’t want to transpile, CommonJS is likely your best bet for today. Since Node uses the CommonJS pattern, you can use npm to pull down 1,000's of packages. CommonJS doesn’t run in the browser without a shim, so you’ll want to use a tool that packages it for the browser like Browserify, Webpack, or JSPM.

7. JS Dependencies Should Be Explicit

This rule closely relates to the rule above. Once you’ve started encapsulating your JavaScript, you need an easy way to reference other modules. That’s the beauty of modern module systems like CommonJS and ES6 modules. You simply specify your dependencies at the top of the file, much like an import or using statement in Java or C#. JavaScript has finally grown up.

//CommonJS
var react = require(‘react’);
//ES6 Modules
import React from ‘React’

8. Transpile to JS

The latest version of JavaScript, EcmaScript 2015 (more commonly known as ES6) was officially released in June. Browsers still lack support for most of the new features, but that doesn’t matter. You can enjoy the long list of new features today using Babel. Babel transpiles ES6 to ES5. And assuming you can live with some performance quirks, you can enjoy the new features today. JavaScript is expected to release new versions once a year now, so we’re likely to be transpiling forevermore. Transpiling gives us the future today.

Or perhaps you love the comfort of strong types? Then consider TypeScript which compiles down to JavaScript.

Bottom line is this:

You don’t have to write ES5 anymore. Consider using an abstraction that gives you extra power.

9. JS Should Have an Automated Build

We’ve already talked about linting, minification, transpilation, and testing. But how do you make all this happen automatically? Simple: With an automated build that watches files. Again, Gulp is a popular tool to tie all this together via its watch function, but Grunt and Webpack are other excellent options to consider. Or, if you’re a whiz at Bash you can simply use npm as a build tool. The point is, don’t expect people to remember to run these things manually. Automate and enjoy the benefits!

10. Use a Framework or Libraries

Pull something awesome off the shelf and get rolling. Need to stay light? Try Backbone or Knockout. Or maybe plain ‘ol jQuery is enough. Want something more full-featured and opinionated? Try, Angular, Ember, or React with Flux.

The point is:

Do not attempt to start from scratch. Stand on the shoulders of giants.

React with Flux is my current favorite combo for client-side dev. That’s why I just published a comprehensive Pluralsight course on the topic. In the course I walk through a build process that implements many of the practices above. The starter kit is on Github.

Regardless of which framework you pick, make sure to separate your concerns. Which leads to the next point…

11. JS Should Separate Concerns

It’s easy to get in the habit of placing all JavaScript in a single file, or to blindly follow the advice of your framework. Don’t forget the lessons you’ve learned on the server when you move to the client.

By separating concerns, I don’t mean merely separating models, views and controllers like you do in MV* style frameworks like Angular and Knockout. I’m saying this:

Think like a server-side developer when writing JavaScript. Separate your presentation from your business logic and data access.

This means AJAX calls should all be in one spot. Create a centralized client-side “data access layer”. This also means logic that doesn’t have to be part of the presentation layer framework you choose should reside in separate “POJOs” (Plain ‘ol JavaScript objects). Business logic modules should contain plain JavaScript — in other words, no framework specific code should reside inside. This makes the logic easy to reuse, easy to test, and it’s not impacted when you decide to move from Angular to the hot new flavor of the month.

12. Use a Starter Kit

That’s a lot to keep track of. And it’s silly to start out each new project with a blank slate. Instead, sit down with your team and decide how you want to build JavaScript projects. Build a starter kit that implements a simple example so everyone has a clear, shared vision on how to get things done.

A starter kit should include linting, minification, bundling, a production build, and a few example automated tests. I suggest including a simple example app that puts this all to use. Then provide a command that removes the starter kit and places the project in a state that’s ready for development.

My starter kit is React Slingshot. I build this starter kit from scratch in my new course “Building Applications in React and Redux in ES6”.

And even though my starter kit is specific to React, if you’re in Angular, Backbone, etc, the core principles and features remain relevant. That said, be sure to Google for other starter kits for inspiration.

So why use a starter kit? A starter kit creates a pit of success. It makes following your team’s agreed list of best practices automatic. A good starter kit makes doing the right thing the easy thing.

Well, That Was Overwhelming.

Yes it was.

We’ve entered an era where the front-end is complicated enough that we need front-end specialists.

Don’t expect everyone on your team to understand how to do all this in detail. Agree on a starter kit that codifies all your decisions. This way, everyone can start with the same solid foundation on your next project.

See things missing? Disagree? Chime in on Reddit.

Cory House is the author of multiple Pluralsight courses including “Building Applications with React and Flux”, “Building Applications in React and Redux in ES6” and “Clean Code: Writing Code for Humans”. He is a Software Architect at Vinsolutions and trains software developers internationally on software practices like front-end development and clean coding. Cory is a Microsoft MVP, and founder of outlierdeveloper.com.

--

--

Cory House

Pluralsight Author, Principal at reactjsconsulting.com, Software Architect, Microsoft MVP, Speaker, Clean Coder, Aspiring Outlier.