JavaScript Standards and Guidelines

Execution and Performance

Coding conventions mentioned here do not affect the execution (runtime) of a script. However, the readability is very important for code in development. These guidelines make it easier for a team when there are many developers working on the same project.

Naming Convention / Variable Names

  • Variables and functions names can be written in camelCase or PascalCase. camelCase is preferable.
  • Global variables and constants should be written in UPPERCASE
  • Do NOT start a variable, function name with $ or include a hyphen (-)

White Spaces

Put spaces before and after an operator ( = + - * / )

var a = x + y;

Put a space after a comma

var cars = ['Volvo', 'Nissan', 'Toyota'];

Indentation

Use a tab character or 4 spaces to indent a code block.

function MakeDisplay(root){
	var ul = genElem('ul', null, {'class': 'CW-display'});
	root.appendChild(ul);
	var arr = [];
	for (var i = 0; i < 8; i++){
		arr[i] = genElem('li');
		ul.appendChild(arr[i]);
	}
	return arr;
}

Control Structures and Code Blocks

  • The opening bracket should be at the end of the first line
  • Have the close bracket in a new line, without any leading space
  • Do NOT end a complex statement with a semicolon

Functions

function toCelsius(fahrenheit) {
	return (5 / 9) * (fahrenheit - 32);
}

Loops

for (i = 0; i < 5; i++) {
	x += i;
}

Conditions

if (time < 20) {
	greeting = "Good day";
}
else {
	greeting = "Good evening";
}

Object Definitions

  • Opening bracket should be at the end of the same line as the object name.
  • Put a colon and one space between each property-value pair.
  • Put only string values in quotes.
  • Do NOT put a comma at the end of the last property-value pair.
  • Place the closing bracket on a new line, without leading spaces.
  • End an object definition with a semicolon.

var person = {
	firstName: 'John',
	lastName: 'Doe',
	age: 50,
	eyeColor: 'blue'
};