Skip to content

Instantly share code, notes, and snippets.

@jameswyse
Last active August 29, 2015 14:14
Show Gist options
  • Save jameswyse/73afc630b88a70779578 to your computer and use it in GitHub Desktop.
Save jameswyse/73afc630b88a70779578 to your computer and use it in GitHub Desktop.

Whether you use 2 spaces or 4 spaces, there are a few simple things that can make your code easier to read. We've been using them in all the hapi modules for over 4 years now.

Required modules

JavaScript makes is harder than most languages to know where variables are coming from. Variables assigned required modules are particularly important because they represent a singleton object shared with the entire application. There are also globals and module globals, along with function variables and arguments.

Traditionally, variables starting with an uppercase letter represent a class that must be instantiated using new. This was an important semantic in the early days of JavaScript but at this point, if you don't know Date requires new Date() you are probably very new. We have adopted CamelCase variable names for all module global variables which are assigned required modules:

var Hapi = require('hapi');

Note that you cannot new Hapi(), only new Hapi.Server(). In this style, the exported object from the modules always exposes an object which contains the API. This means a single function module should still export an object with the single method as an object property:

exports.add = function (a, b) {

    return a + b;
};

This makes it trivial to identify which variables in your code represent required modules. The language itself does contain a few uppercase variables but those are well known and should not cause any confusion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment