- Variable and function names must always be written in camelCase.
- All variable and constant names must start with a letter.
- Underscores in variable and constant names may be used when necessary.
- Hyphens must not be used.
- All local variables in a function must be declared with the
varkeyword. - Global variables and constants must be written in UPPERCASE.
- The use of global variables should be minimized.
var firstName = 'John';
var lastName = 'Doe';- Always put spaces around operators (
=+-*/), and after commas: - Calculations should be used in brackets.
var x = (y + z);
var values = ["Volvo", "Saab", "Fiat"];- Statements must end with a semicolon
var name = "John Doe";- Complex statements must always use brackets.
- The opening bracket must be set at the end of the first line.
- Before the opening bracket one space must be set.
- The closing bracket must be set on a new line, without leading spaces.
- 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;
}Conditionals:
if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}- The opening bracket must be placed on the same line as the object name.
- Use colon plus one space between each property and its value.
- Quotes must be placed around string values and must not be placed around numeric or boolean values.
- Do not add a comma after the last property-value pair.
- Place the closing bracket on a new line, without leading spaces.
- Always end an object definition with a semicolon.
- Short objects can be written in one line, using spaces only between properties.
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};- Never declare Number, String, or Boolean Objects
var x = "John";
var y = new String("John");
(x === y) // is false because x is a string and y is an object.var x = new String("John");
var y = new String("John");
(x == y) // is false because you cannot compare objects.- Declarations must be placed on top
// 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;- Use
{}instead ofnew Object() - Use
""instead ofnew String() - Use
0instead ofnew Number() - Use
falseinstead ofnew Boolean() - Use
[]instead ofnew Array() - Use
/()/instead ofnew RegExp() - Use
function (){}instead ofnew Function()
- Comparison with value and type
===is strongly recommended.
"1" === 1 // false
1 === 1 // trueeval()must be avoided, if possible.