-
Notifications
You must be signed in to change notification settings - Fork 19
JavaScript Style Guide
Jason Best edited this page Feb 5, 2015
·
4 revisions
See installing GruntJS on the main readme. There is a grunt task for jshint, simply run: grunt jshint from the command line.
- Indent using 4 spaces
- No end of line whitespace
- Use a blank line with no whitespace after blocks
- Use a space after if/else/for/while/try
- Use a space after variable declaration and assignment
Good
var x = 10;
if (something) {
} else {
}
for (x = 0; x < 10; x++) {
}
while (true) {
}
try {
} catch (e) {
}
// No space after function keyword
function(x) {
}Bad
var x=10; // Use spacing
// No space after the if or after the paren
if(something){
}
// No indent
if (true) {
}
// Use curly braces
if (true)
callSomething();
// Use multiple lines
if (true) { callSomething();}
if (someting) {
}
doSomethingAfter(); // Put a blank line after the previous block- Always use curly brackets
- The starting bracket should go on the same line as the keyword
- The ending bracket should be on a new line by itself
Good
if (something) {
} else {
}
for (x = 0; x < 10; x++) {
}
while (true) {
}
try {
} catch (e) {
}Bad
// Always use curly braces
if (true)
callSomething();
// Use multiple lines
if (true) { callSomething();}- No spaces for parens when calling a function
- Only use a space after the comma for multiple arguments
Good
noArgsCall();
callSomething(arg);
callSomething2(arg1, arg2);Bad
noArgsCall ( );
callSomething ( arg );
callSomething2 ( arg1 , arg2 );- Use one var at the top of the function
- Use a newline after the semicolon
Good
var x, y, z;
function something(x) {
var x, y,
z = true;
// Code
}
function somethingToo(x) {
var x = 'something',
y = 'something',
i;
// Code
for (i = 0; i < 10; i++) {
}
}Bad
var x;
var y;
var z;
function something(x) {
var x;
var y;
var z = true;
// Code
}
function somethingToo(x) {
// var i is declared separate from the others
for (var i = 0; i < 10; i++) {
// All vars should be at the top of the function
var x = 'something',
y = 'something';
}
}- Always use === in favor of ==
- Always use a single quote, so templates can use double quotes for HTML attributes
Example
//Template
itemTemplate: new Simplate([
'<span id="something">{%: $.AccountName %}</span>'
])- Put comment above line you are commenting, with some exception for inline comments
- Use JSDoc (http://usejsdoc.org/) comments when possible
Example
// Localized
someText: 'SalesLogix'
/*
* @ param {string} name Name of person
*/
function callByName(name) {
}
while (/*TODO: Remove this*/ true) {
}