JavaScript Style and Layout

Updated Wednesday, 24th June 2015
A quick primer on some of the good practices and styles you should use when writing JavaScript.

This page was published 6 years and 7 months ago. Please be aware that due to the passage of time, the information provided on this page may be out of date or otherwise inaccurate, and any views or opinions expressed may no longer be relevant. Some technical elements such as audio-visual and interactive media may no longer work. For more detail, see our Archive and Deletion Policy.

JavaScript has a range of different style conventions designed to keep your code in order. If you want to start learning more about programming and JavaScript in general, try Getting started with Programming using JavaScript.

Separating program statements

A program consists of a sequence of statements. You can think of a statement as being the equivalent of a sentence in the JavaScript language. In the case of an ordinary sentence its end is marked by a full stop, but to mark the end of a JavaScript 'sentence' we use, not a full stop, but a semicolon (;). The semicolon tells the JavaScript interpreter – the part of the browser that is responsible for running JavaScript programs – where one statement ends and the next one begins.

JavaScript will also accept a break between lines as a separator, providing that what appears on the first line forms a proper statement. However we recommend you do not rely on line breaks to separate statements but always insert a semicolon.

We also recommend you keep statements to one per line, to make the code easier to read.

Naming things

Variables

Variables are essentially named locations for holding data. Before attempting to use a variable you should declare it using the keyword var, for example
 

var myFirstVariable;

In JavaScript, names – also known as identifiers – must begin with a letter and contain only letters and numbers.
As long as you follow this, names can be anything you like, but your programs will be much easier to understand if you choose identifiers that are 'self-documenting', so that the reader can tell what their purpose is in the program.

For example, a variable to hold a value which represents a maximum rainfall could be named something like maxRainfall. A variable to record a year of birth would probably be named yearOfBirth.

On OpenLearn we follow the convention that a variable name will always start with a lower-case letter, not a capital one. We also use so-called camel-backed identifiers. If a name is based on two or more words run together, the start of each word after the first is marked by using a capital letter.

Functions

A function is a chunk of code that performs a specific subtask. For example a function might be written to accept temperatures in Fahrenheit and convert them to Celsius.
The names of functions should obey the same rules as those for variables, including being meaningful, starting with a lower-case letter and using the camel-backed convention. For instance, the function described above might be named fahrenheitToCelsius.

Braces

Braces { and } are often called 'curly brackets'. Braces are used in JavaScript to bundle together a series of statements into what is called a compound statement (or program block). Everything between the opening brace { and the closing one } is then treated as a single statement.

Note that although a single, i.e. non-compound, statement ends with a semicolon, a compound statement does not. There is no semicolon after the closing brace.

Our convention is that opening and closing braces both occupy separate lines of their own, with nothing else on those lines, and each opening brace and its corresponding closing brace should line up vertically.

The example below illustrates all this (don’t worry at this point about what the statements do, we are only interested in the separators and layout).

{
   temp = temp – 32;
   temp = (temp * 9) / 5;
   return temp;
}

Spaces

Adding extra spaces can help make code more readable. On OpenLearn we usually add a space

  • after the keywords if, else, while, for
  • on either side of the assignment operator =
  • on either side of numeric, string and Boolean operators.

The example below illustrates these conventions. Again the details of the code are not important, so don’t worry if you don’t understand them at this stage. So you can make out better where spaces have been inserted, we have temporarily replaced each by a large dot (•).

var temp2•=•fahrenheitToCelsius(temp1);
if•(temp2•>•100)
{
    window.alert(temp1•+•' is above boiling point.');
}

Of course, what you see above is not legal JavaScript. The actual code would be as follows:

var temp2 = fahrenheitToCelsius(temp1);
if (temp2 > 100)
{
    window.alert(temp1 + ' is above boiling point.');
}

It is also common to add spaces after commas in lists. Again using dots:

var suitArray•=•['clubs',•'diamonds',•'hearts',•'spades'];

In reality the code would look like this

var suitArray = ['clubs', 'diamonds', 'hearts', 'spades'];

Whether you follow our conventions for extra spaces is entirely up to you. However you should try to make sure you are consistent. Don’t for example write

var age1 = 23;

and then a few lines further on

var age2=45;

or worse still

var age3= 61;

Comments

Comments are used to make it easier for a human reader to understand what a program does and how it does it. By documenting what the purpose of code is and when it can be used, you make it possible for another programmer to use what you have written. And by documenting how it works you make it much easier for you or anyone else to change the program should it becomes necessary.

Since comments are intended only for human readers they are ignored by the JavaScript interpreter. We can indicate a comment in two ways.

The symbol // (two forward slashes) tells JavaScript to ignore anything on the remainder of that line.

// This is a comment.

The pair of symbols /* and */ tells JavaScript to ignore anything in between them.

/* This is another comment. */

This style of comment may extend over several lines.

/*
 * This style can extend over several lines
 * and is used for longer comments.

 */

We advise you to comment your programs fairly thoroughly. What seems self-explanatory to you won't usually be so to another person; moreover you yourself will rapidly forget how your code is supposed to work if you don’t document it.

Indentation

Programs often contain parts which are nested inside others. This nesting arises from control structures, such as selection (using if and else) and repetition (using while or for). Nested portions may in turn have subordinate parts nested inside them, and so on.

It soon gets hard for a reader to keep track of the nesting, so to make it easier to follow programmers use indentation. A block of code nested within a larger structure will be indented by adding spaces in front of it, so that it is shifted further to the right compared with its surroundings. If the nested block nests yet another block within it, the latter will be indented still further right, and this continues. There can be several levels of nesting, and the most deeply nested code will be indented furthest to the right. As a matter of interest, there are even programming languages that exist which rely entirely on indentation to express the program structure.

The following code extract has three levels. Note the way in which each opening brace and its corresponding closing brace are vertically aligned, and also how the indentation lets us see clearly how the ifs and elses match up.

if (temperature <= 0)
{
    document.write('It is freezing');
}
else
{
    if (temperature < 15)
        {
            document.write('It is cold');
        }
        else
        {
            if (temperature < 25)
        {
            document.write('It is a nice day'); } else {
            document.write('It is hot!');
        }
    }
}

Normally each indent is four spaces, we have chosen in all our examples to indent by four spaces e.g.

if (temperature <= 0)
{
••••document.write('It is freezing')
}

Whether you indent your code by 3 or 4 spaces, it doesn't matter, what matters is that you should be consistent.

Evenly spaced fonts

When you indent code the vertical alignment won't be correct unless you use an evenly-spaced font, in which each letter (and space) is exactly the same width. Most fonts are not evenly spaced. The examples below demonstrate the difference. The first is evenly-spaced, the second not.

Courier New Font Arial font
iii iii
nnn nnn
mmm mmm

The font we recommend is Courier New, available on most systems. A good font size is 10 point, because that helps with fitting long lines of code into the width of the page.

Formatting long lines of code

Sometimes a JavaScript statement can get much longer than a normal page width and you will want to wrap it onto several lines for readability. Note that you cannot break a line in the middle of a keyword or identifier – otherwise JavaScript will not recognise it correctly – and neither can it be broken in the middle of a string, for reasons we expand on shortly.

When a line is broken it will continue again on the next line. We don't mandate any fixed rules for the indentation of the continuation line – the best guide to use is readability – but you should try to be reasonably consistent and not just indent continuation lines haphazardly.

The following are some simple guidelines for deciding where to break a line.

Break line before or after the assignment operator (=)

For example:

var name = window.prompt('Please enter the first name of your second cousin', '');

can be reformatted as:

var name =
window.prompt('Please enter the first name of your second cousin', '');

or as:

var name
= window.prompt('Please enter the first name of your second cousin, '');

Break line before or after a function’s opening bracket

For example:

var name = window.prompt('Please enter the first name of your second cousin', '');

can be reformatted as

var name = window.prompt(
'Please enter the first name of your second cousin', '');

Break line before or after the string concatenation operator (+)

For example:

document.write('You are ' + differenceInYears(today, birthDay) + 'years old.');

can be reformatted as:

document.write('You are '
               + differenceInYears(today,birthDay)
               + ' years old.');

or as:

document.write('You are ' +
               differenceInYears(today, birthDay) +
               ' years old.');

Do not break in the middle of a string

A statement such as

var longString = 'This was a very long string indeed '
                  + 'and there was never any realistic possibility that it '
                  + 'could be made to fit on to one line.';

will cause an error, because the line break will make it look to the JavaScript interpreter as if there is a string that has not ended with a single quote as it ought to have done (this is called an unterminated string literal.)

The solution is to split the string into sections and use the concatenation operator, like this

var longString = 'This was a very long string indeed ' +
                 'and there was never any realistic possibility that it ' +
                 'could be made to fit on to one line.';

When code is copied and pasted into a word-processed document the line wrapping may get altered. Try to make sure that you break each line early enough so that the word-processed version still ends up formatted correctly.

 

Ratings & Comments

Share this free course

Copyright information

For further information, take a look at our frequently asked questions which may give you the support you need.

Have a question?