JavaScript Coding Standards and Best Practices
Version 1.0
Prepared By: Aakash Thakkar
Document Revision History:
Version
Primary Author(s)
Description
Date
1.0
Aakash Thakkar
JavaScript Coding Standards and
Best Practices (First Draft)
12May2015
Introduction
JavaScript first appeared almost 20 years ago in 1995, and as of today it has continuously evolved since and is most commonly used as part of web browsers , whose implementations allow clientside scripts to interact with the user , control the browser, communicate asynchronously, and alter the document content that is displayed. It is also used in serverside network programming with runtime environments such as Node.js , game development and the creation of desktop and mobile applications.
This document is prepared for you to follow the best practices while writing JavaScript code. Many organizations such as W3Schools, SUN(now Oracle) and Wordpress have released JavaScript coding standards. In this document, I will be covering the best practices and coding standards published by W3Schools.
This document will cover the following :
1. Naming and declaration rules for variables and functions. 2. Rules for spaces, indentations and comments. 3. Practices and principles. By following the coding standards and best practices it will make code readability and maintenance easier.
Standards
1. Naming Conventions
The W3 standards suggests to use camelCase for declaring variables and functions. UPPERCASE for golbal variables and constants.
firstName ="John";
lastName ="Doe";
const MYCONSTANT =7;
2. Spaces around operators
Always put spaces around operators (=, +, , *, /), and after commas.
var x = y + z;
var values =["Volvo","Saab","Fiat"];
3. Code Indentation
Always use 4 spaces for indentations for code blocks, and don’t use TAB key, as different editors use tab key differently.
function toCelsius(fahrenheit) {
return(5/9)*(fahrenheit -32);
}
4. Statement Rules
Always end a simple statement with a semicolon.
var values =["Volvo","Saab","Fiat"];
General rules for Compound statements :
1. Put the opening bracket at the end of the first line. 2. Use one space before the opening bracket. 3. Put the closing bracket in a new line, without leading spaces
4.
Do not end a complex statement with a semicolon.var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
Functions:
function toCelsius(fahrenheit) {
return(5/9)*(fahrenheit -32);
}
Loops:
for(i =0; i <5; i++) {x += i;
}
Conditionals:
if(time <20) {greeting ="Good day";
}else {
greeting ="Good evening";
}
5. Object Rules
General rules for object definitions:
1. Place the opening bracket on the same line as the object name. 2. Use colon plus one space between each property and its value. 3. Use quotes around string values, not around numeric values. 4. Do not add a comma after the last propertyvalue pair. 5. Place the closing bracket on a new line, without leading spaces. 6. Always end an object definition with a semicolon.
Example:
var person = {firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
Short objects can be written compressed, on one line, using spaces only between properties, like this:
var person ={firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
6.Line Length < 80
Lines more than 80 characters can be difficult to read. Try to avoid using more than 80 characters. If no choice use the following practice.
document.getElementById("demo").innerHTML =
"Hello Dolly.";
7. Loading JavaScript in HTML
Use simple syntax for loading external scripts. The type tag is not necessary.
<scriptsrc="myscript.js"></script>
8. Accessing HTML Element
A consequence of using "untidy" HTML styles, might result in JavaScript errors. These two JavaScript statements will produce different results.
var obj = getElementById("Demo")
var obj = getElementById("demo")
9. File Extensions
1. HTML files should have .HTML extension (not .htm). 2. CSS files should have .CSS extension. 3. JavaScript files should have .js extension.
10. Use lowercase for filenames
1. Most web servers (Apache, Unix) are case sensitive about file names 2. london.jpg cannot be accessed as London.jpg. 3. Other web servers (Microsoft, IIS) are not case sensitive. 4. london.jpg can be accessed as London.jpg or london.jpg. 5. If you use a mix of upper and lower case, you have to be extremely consistent. 6. If you move from a case insensitive, to a case sensitive server, even small errors can break your web site. 7. To avoid these problems, always use lower case file names (if possible).
JavaScript Best Practices
1. Avoid using Global Variables and use Local variables
Global variables can be overwritten by other scripts, hence always try and use local variables and try using closures. Also all the local variables must be declared using “var” keyword.
2. Declarations on Top
It is a good coding practice to put all the declarations on the top of each page or function. This will
1. Give cleaner code. 2. Provide a single place to look for local variables. 3. Make it easier to avoid unwanted (implied) global variables. 4. Reduce the possibility of unwanted redeclarations
// Declare at the beginning
var firstName, lastName, price , discount, fullPrice;
// Use later
firstName ="John";
lastName ="Doe";
price =19.90;
discount =0.10;
fullPrice = price *100/ discount;
This also goes for loop variables:
// Declare at the beginning
var i;
// Use later
for(i =0; i <5; i++) {
3. Never Declare Number, String, or Boolean Objects
Always treat numbers, strings, or booleans as primitive values. Not as objects. Declaring these types as objects, slows down execution speed, and produces nasty side effects:
var x ="John";
var y =newString("John");
(x === y)// is false because x is a string and y is an object.
Or even worse,
var x =newString("John");
var y =newString("John");
(x == y)// is false because you cannot compare objects.
4. When doing mathematical operations, JavaScript can convert numbers
to strings:
var x =5+7; // x.valueOf() is 12, typeof x is a number
var x =5+"7"; // x.valueOf() is 57, typeof x is a string
var x ="5"+7; // x.valueOf() is 57, typeof x is a string
var x =5-7; // x.valueOf() is -2, typeof x is a number
var x =5-"7"; // x.valueOf() is -2, typeof x is a number
var x ="5"-7; // x.valueOf() is -2, typeof x is a number
var x =5-"x"; // x.valueOf() is NaN, typeof x is a number
5. Subtracting a string from a string, does not generate an error but
returns NaN (Not a Number):
6. Use === Comparison
The == comparison operator always converts (to matching types) before comparison. The === operator forces comparison of values and type:
0==""; // true
1=="1"; // true
1==true; // true
0===""; // false
1==="1"; // false
1===true; // false
7. Use Parameter Defaults
If a function is called with a missing argument, the value of the missing argument is set to undefined. Undefined values can break your code. It is a good habit to assign default values to arguments.
function myFunction(x, y) {
if(y === undefined) {
y =0;
}
}
8. End Your Switches with Defaults
Always end your switch statements with a default. Even if you think there is no need for it.
switch(newDate().getDay()) {