There are a number of different JavaScript style guides which all have slightly different opinions on what the best format is for JavaScript code. However, there are some core rules that really should be applied to all JavaScript, and they are listed below!

Golden Rules

Whatever style guide you go with, there are some golden rules you should always follow…

  1. Be Consistent: When writing new code in an existing file, even if it’s not using the style you would normally use - try to make your code look as similar to the existing code as possible. The worst code is the ones that have a mix of random styles.

  2. Use Comments: When you return to your code in 1, 3 or 18 months - you will really thank yourself for having spent the additional 20 seconds writing a single line comment about your weird function.

  3. Reduce Globals: You should try to use the least number of global variables you can to get your code to work. Every global variable you add increases the risk of having a clash with another JavaScript file.

  4. Always Use Semicolons: They don’t cost anything and they only help to reduce the potential for introducing errors later on. They also make it explicitly clear when your statements end.

  5. Indent Your Code: When starting a new execution block (section of code surrounded by curly braces) you should always tab in your code. See the examples below!

Example Code

While there are many nuances of what good/bad code looks like depending on who you talk too, you will generally see that most JavaScript looks something similar to the following code;

function functionNameLikeThis(parameterOne, parameterTwo) {
    if (something || somethingElse) {
        // Do Something
    } else {
        // Do Something Else
    }
};

var myString = "Hello World";
var myNumber = 10.0;
var myArray = [1, 2, 3];

var myObject = {
    a: "Hello",
    b: 4.0,
    c: true
};

myObject.doSomething = function(parameterOne, parameterTwo) {
    // Do Something
};

i.e.

  • Names for functions, variables and parameters use camelCaseStyle.
  • The curly brackets for fuctions and if statements are usually on the same line as the if/for statement itself.
  • There are usually (noSpacesBetweenBracketsAndWords), but (oftenThereis, oneSpaceAfter, aComma).
  • Statements end with semi-colons.
  • Code inside of functions, if-statements and loops is indented with a tab or N spaces.
  • There are spaces around equals signs (=) when assigning variables.