12 Rules for Professional JavaScript in 2015

proffesional-javascriptJavaScript 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. 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 downloadedevery 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, butGulp with gulp-uglify is a low-friction and automated way to get rolling.

4. JS Belongs at the Bottom

If you place <script> tags in <head>, they block rendering. Scripts in <head> must be loaded before the body is displayed. So placing <script> tags at the bottom of the page just before </body> allows the page to load visibly without waiting for your scripts to download. This helps improve perceived performance by giving your users something to view sooner. If you’re writing JavaScript that must be in <head>, consider using something like jQuery’s $(document).ready so your script doesn’t execute until the DOM is ready.

5. 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 withgulp-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?

6. 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 automatedtests.

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 suggestJasmine if you’re new to JavaScript testing and Mocha with Chai if you want the ultimate configurability.

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

8. 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’

9. 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 TypeScriptwhich 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.

10. 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!

11. Use a Framework or Libraries

Pull something awesome off the shelf and get rolling. Need to stay light? TryBackbone 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…

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

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.