Skip to content

Instantly share code, notes, and snippets.

@fleishmanhillard
Created April 4, 2014 21:41
Show Gist options
  • Save fleishmanhillard/9983665 to your computer and use it in GitHub Desktop.
Save fleishmanhillard/9983665 to your computer and use it in GitHub Desktop.
JavaScript style guide with coding standards and best practices.

JavaScript (jQuery) Style Guide

All rules and guidelines in this document apply to jQuery files unless otherwise noted.

The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.

Most sections are broken up into two parts:

  1. Overview of all rules with a quick example
  2. Each rule called out with examples of do's and don'ts

Icon Legend:

· Space, Tab, Enter/Return

Table of Contents

  1. Files
    1. File Format
    2. Filename
  2. Skeleton
  3. jQuery Initialization
    1. Document Ready
  4. Namespaces
    1. Namespace Declaration
    2. Namespace Name
  5. Comments
    1. Single-line Comments
    2. Multi-line Comments
    3. Comments
    4. Blocks of Code
    5. Ambiguous Numbers
    6. External Variables
  6. Formatting
    1. Line Length
    2. Line Indentation
    3. Blank Lines
    4. Text Alignment
    5. Method Chaining
    6. Trailing Whitespace
    7. Keywords
    8. Variables
    9. Global Variables
    10. Constants
    11. Statements
    12. Operators
    13. Unary Operators
    14. Concatenation Plus
    15. Single Quotes
    16. Double Quotes
  7. Functions
    1. Function Name
    2. Function Prefix
    3. Function Call
    4. Function Arguments
    5. Function Declaration
    6. Function Return
  8. Control Structures
    1. If, Else if, Else
    2. Switch, Case
    3. While, Do While
    4. For, Each
    5. Try, Catch
  9. Best Practices
    1. Variable Initialization
    2. Globals
    3. Objects, Arrays
    4. Explicit Expressions
    5. Event Handling
    6. Ajax
    7. Selectors
    8. Performance
    9. Code Groupings

1. Files

This section describes the format and naming convention of jQuery files.

File Format

  1. Character encoding MUST be set to UTF-8 without BOM
    • Sublime.app → FileSave with EncodingUTF-8
  2. Line endings MUST be set to Unix (LF)
    • Sublime.app → ViewLine EndingsUnix

Filename

  1. Letters MUST be all lowercase
    • e.g. foo.js
  2. Words MUST be separated with a hyphen
    • e.g. foo-bar.js
  3. Version SHOULD be used if this is a js file that will be updated frequently
    • e.g. foo-bar-1.4.2.js
  4. Minified MUST be appended to the filename if the js file is minified
    • e.g. foo-bar-1.4.2.min.js
  5. Plugins SHOULD be prefixed with jquery
    • e.g. jquery.foo.js

Table of Contents

2. Skeleton

This section showcases a barebones jQuery file with its minimum requirements. Javascript files that aren't utilizing the jQuery library may use line by line breakdown #2.

  1. Line by line breakdown:
  • Line 1: jQuery open tag
  • Line 2: Blank line
  • Line 3: Your code
  • Line 4: Blank line
  • Line 5: jQuery closing tag
  • Line 6: Blank line
  • Line 7: End-of-file comment
  • Line 8: Blank line
jQuery(document).ready(function($) {

// your code

});

// EOF
  1. Line by line breakdown (vanilla javascript):
  • Line 1: Your code
  • Line 2: Blank line
  • Line 3: End-of-file comment
  • Line 4: Blank line
// your code

// EOF

Table of Contents

3. jQuery Initialization

This section describes the initialization of the jQuery environment.

  1. Document Ready MUST be initialized in noConflict mode
    • i.e. jQuery(document).ready(function($) { ...

Table of Contents

1. Document Ready

jQuery document ready must be initialized in noConflict mode

✖ Incorrect

$(document).ready(function() {

 // your code //
 
});

// EOF

↳ Incorrect because $ is not a safe variable to use when initializing jQuery document ready. Other libraries may utilize this variable and overwrite its value.

✔ Correct

jQuery(document).ready(function($) {
	
// your code //
	
});

// EOF
(function($) {	

// your code //

}(jQuery));

// EOF

↳ Shorthand version of the previous correct method

 (function($, window, document) {
    
   $(function() {

    // your code //

   });
   
  }(window.jQuery, window, document));
  
  // EOF
  

↳ Scoped version of the previous correct method

jQuery Initialization

4. Namespaces

This section describes how to use a namespace in javascript.

  1. Namespace declaration MUST be the first statement and MUST be followed by a blank line
    • i.e. var MyNamespace = MyNamespace || {};
  2. Namespace name MUST start with a capital letter and MUST be camelcase
    • e.g. var MyFooBar = MyFooBar || {};

Table of Contents

1. Namespace Declaration

Namespace declaration MUST be the first statement and MUST be followed by a blank line.

✖ Incorrect

console.log('js-enabled');
var FooBar = FooBar || {};

↳ Incorrect because var FooBar = FooBar || {}; is not the first statement.

var FooBar = FooBar || {};
console.log('js-enabled');

↳ Incorrect because var FooBar = FooBar || {}; is not followed by a blank line.

✔ Correct

var FooBar = FooBar || {};
var BarFoo = BarFoo || {};

console.log('js-enabled');

↳ Multiple namespace example.

Namespaces

2. Namespace Name

Namespace name MUST start with a capital letter and MUST be camelcase.

✖ Incorrect

var foobar = fooBar || {};

↳ Incorrect because fooBar does not start with a capital letter.

var FOOBAR = FOOBAR || {};

↳ Incorrect because FOOBAR is not written in camelcase.

✔ Correct

var FooBar = FooBar || {};

Namespaces

5. Comments

This section describes how comments should be formatted and used.

  1. Single-line comments MUST use a forward slashes
    • e.g. // My comment
  2. Multi-line comments MUST use the block format
    • i.e. /** * My comment */
  3. Comments MUST be on their own line
    • i.e. // My comment
  4. Blocks of code SHOULD be explained or summarized
    • e.g. // Compare user accounts from export against expired accounts in system
  5. Ambiguous numbers MUST be clarified
    • e.g. // 1,000 processable records per hour API limit
  6. External variables MUST be clarified
    • e.g. // Global variable defined via wp_localize_script in functions.php

Table of Contents

1. Single-line Comments

Single-line comments MUST use forward slashes.

✖ Incorrect

jQuery(document).ready(function($) {

/* This is a comment */

});

↳ Incorrect because it uses /* and */ for a single-line comment.

✔ Correct

jQuery(document).ready(function($) {

// This is a comment

}); 

// EOF

Comments

2. Multi-line Comments

Multi-line comments MUST use the block format.

✖ Incorrect

jQuery(document).ready(function($) {

// This is a
// multi-line
// comment

});

// EOF

↳ Incorrect because it uses // for a multi-line comment.

✔ Correct

jQuery(document).ready(function($) {

/**
 * This is a
 * multi-line
 * comment
 */

});

// EOF

Comments

3. Comments

Comment MUST be on their own line.

✖ Incorrect

jQuery(document).ready(function($) {

print_welcome_message(); // Prints welcome message

}); 

// EOF

↳ Incorrect because // Prints welcome message is not on its own line.

✔ Correct

jQuery(document).ready(function($) {

// Prints welcome message
print_welcome_message();

}); 

// EOF

Comments

4. Blocks of Code

Blocks of code SHOULD be explained or summarized.

~ Acceptable

var users = ['John', 'Jane', 'Jim'];

$.each(users, function(key, value) {
	// ...
	} else {
		// ...
	}
	if (expr2) {
		// ...
	} else if (expr3) {
		// ...
	} else {
		// ...
	}
	// ...
});

↳ Acceptable, but block of code should be explained or summarized.

✔ Preferred

/**
 * Get active website bloggers with profile photo for author page.
 * If no photo exists on website, check intranet.
 * If neither location has photo, send user email to upload one.
 */
var users = ['John', 'Jane', 'Jim'];

$.each(users, function(key, value) {
	if (expr1) {
		// ...
	} else {
		// ...
	}
	if (expr2) {
		// ...
	} else if (expr3) {
		// ...
	} else {
		// ...
	}
	// ...
});

Comments

5. Ambiguous Numbers

Ambiguous numbers MUST be clarified.

✖ Incorrect

while (expr && x < 1000) {
	// ...
}

↳ Incorrect because 1000 is not clarified.

✔ Correct

// Script times out after 1,000 records
while (expr && x < 1000) {
	// ...
}

Comments

6. External Variables

External variables MUST be clarified.

✖ Incorrect

var users = _wpcf7.cache;

// ...

jQuery.each(users, function(index, user) {
	// ...
});

↳ Incorrect because source of users is not clear.

✔ Correct

var users = _wpcf7.cache;

// ...

// _wpcf7 defined as a global object outside of document ready by contact form 7 plugin
jQuery.each(users, function(index, user) {
	// ...
});

Comments

6. Formatting

This section outline various, general formatting rules related to whitespace and text.

  1. Line length MUST NOT exceed 80 characters, unless it is text
    • i.e. |---- 80+ chars ----| → refactor expression and/or break list values
  2. Line indentation MUST be accomplished using tabs
    • i.e. function func() { ... }
  3. Blank lines SHOULD be added between logical blocks of code
    • i.e. ... ...
  4. Text alignment MUST be accomplished using spaces
    • i.e. var foo · · · = ...;
  5. Method chaining MUST indent when making long method chains
    • e.g. $('#foo .bar') .hide() ↵``.css('opacity', .9) .show();
  6. Trailing whitespace MUST NOT be present after statements or serial comma break or on blank lines
    • i.e. no ... · · · ...
  7. Keywords MUST be all lowercase
    • e.g. false, true, null, etc.
  8. Variables MUST start first word lowercase and subsequent words MUST start with uppercase letter
    • e.g. var welcomeMessage;
  9. Global variables MUST be declared one variable per line and must be preceeded by a comment declaring them to be global.
    • e.g. var foo; var bar;
  10. Constants MUST be all uppercase and words MUST be separated by an underscore
    • e.g. WELCOME_MESSAGE
  11. Statements MUST be placed on their own line and MUST end with a semicolon
    • e.g. welcome_message();
  12. Operators MUST be surrounded by a space
    • e.g. var total = 15 + 7;, foo .= '';
  13. Unary operators MUST be attached to their variable or integer
    • e.g. index++, --index
  14. Concatenation plus MUST be surrounded by a space
    • e.g. alert('Read:' + welcomeMessage);
  15. Single quotes MUST be used
    • e.g. alert('Hello, World!');
  16. Double quotes SHOULD NOT be used
    • e.g. alert('Read: ' + welcomeMessage);

Table of Contents

1. Line Length

Line length MUST NOT exceed 80 characters, unless it is text.

✖ Incorrect

if ( jQuery.inArray('Slumdog Millionaire', movies) !== -1 && jQuery.inArray('Silver Linings Playbook', movies)!== -1 && jQuery.inArray('The Lives of Others', movies)!== -1 && jQuery.inArray('The Shawshank Redemption', movies)!== -1){
	// if body
}

↳ Incorrect because expression exceeds 80 characters and should be refactored.

var myMovies = ['Slumdog Millionaire', 'Silver Linings Playbook', 'The Lives of Others', 'The Shawshank Redemption'];
var length = myMovies.length;
for ( var i = 0 ;  i < length; i++ ) {
  if ( jQuery.inArray(myMovies[i], array ) > -1) {
   // do whatever you want.
}

↳ Incorrect because arguments exceed 80 characters and should be placed on their own line.

~ Acceptable

var text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec posuere rutrum tincidunt. Duis lacinia laoreet diam, nec consectetur magna facilisis eget. Quisque elit mauris, auctor quis vulputate id, sagittis nec tortor. Praesent fringilla lorem eu massa convallis ultricies. Maecenas lacinia porta purus, sollicitudin condimentum felis mollis a. Proin sed augue purus. Quisque scelerisque eros vitae egestas porta. Suspendisse vitae purus justo. Pellentesque justo nunc, luctus quis magna sit amet, venenatis rutrum ante. Nam eget nisi ultricies, sodales lectus vel, luctus dui. Cras pellentesque augue vitae nulla laoreet convallis. Mauris ut turpis mollis, elementum arcu eu, semper risus. Mauris vel urna ut felis blandit dictum. Aliquam sit amet tincidunt arcu. Nunc et elit quam. Aliquam hendrerit magna ut lacus semper consequat blandit eu ipsum.';

↳ Acceptable because line length was exceeded due to text, not code.

✔ Correct

var myMovies = array[
	'Slumdog Millionaire',
	'Silver Linings Playbook',
	'The Lives of Others',
	'The Shawshank Redemption'
];

var hasAllMovies = true;

jQuery.each(myMovies, function(key, myMovie)) {
	if (jQuery.inArray('Slumdog Millionaire', movies)!== -1) {
		hasAllMovies = false;
	}
});

if (hasAllMovies) {
	// if body
}

var someLongVariable = get_something_else(
	'from_some_other_function',
	'another_long_argument'
);

Formatting

2. Line Indentation

Line indentation MUST be accomplished using tabs.

✖ Incorrect

function print_welcome_message() {
    alert('WELCOME_MESSAGE');
}

});

↳ Incorrect because spaces are used to indent alert('WELCOME_MESSAGE'); instead of a tab.

✔ Correct

function print_welcome_message() {
	alert('WELCOME_MESSAGE');
}

Formatting

3. Blank Lines

Blank lines SHOULD be added between logical blocks of code.

~ Acceptable

var myMovies = [
	'Slumdog Millionaire',
	'Silver Linings Playbook',
	'The Lives of Others',
	'The Shawshank Redemption'
];
var hasAllMovies = true;
jQuery.each(myMovies, function(key, myMovie)) {
	if (jQuery.inArray(myMovie, movies)!== -1) {
		hasAllMovies = false;
	}
});
if (hasAllMovies) {
	// if body
}

↳ Acceptable, but can make scanning code more difficult.

✔ Preferred

var myMovies = [
	'Slumdog Millionaire',
	'Silver Linings Playbook',
	'The Lives of Others',
	'The Shawshank Redemption'
];

var hasAllMovies = true;

jQuery.each(myMovies, function(key, myMovie)) {
	if (jQuery.inArray(myMovie, movies)!== -1) {
		hasAllMovies = false;
	}
});

if (hasAllMovies) {
	// if body
}

Formatting

4. Text Alignment

Text alignment MUST be accomplished using spaces.

✖ Incorrect

var movieQuotes = [
	'slumdog_millionaire'		: 'When somebody asks me a question, I tell them the answer.',
	'silver_linings_playbook'	: 'I opened up to you, and you judged me.',
	'the_lives_of_others'		: 'To think that people like you ruled a country.',
	'the_shawshank_redemption'	: 'Get busy living, or get busy dying.'
];

↳ Incorrect because tabs are used instead of spaces to vertically align :.

var movieQuotes = [
    'slumdog_millionaire'       : 'When somebody asks me a question, I tell them the answer.',
    'silver_linings_playbook'   : 'I opened up to you, and you judged me.',
    'the_lives_of_others'       : 'To think that people like you ruled a country.',
    'the_shawshank_redemption'  : 'Get busy living, or get busy dying.'
];

↳ Incorrect because spaces are used instead of tabs to indent array keys.

✔ Correct

var movieQuotes = [
	'slumdog_millionaire'       : 'When somebody asks me a question, I tell them the answer.',
	'silver_linings_playbook'   : 'I opened up to you, and you judged me.',
	'the_lives_of_others'       : 'To think that people like you ruled a country.',
	'the_shawshank_redemption'  : 'Get busy living, or get busy dying.'
];

Formatting

5. Method Chaining

Long method chains MUST be indented.

✖ Incorrect

jQuery('#movies').find('.movie').highlight().end().find('.selected').updateCount();

↳ Incorrect because methods are on a single line and not indented.

✔ Correct

jQuery('#movies')
	.find('.movie')
	.highlight()
	.end()
	.find('.selected')
	.updateCount();

Formatting

6. Trailing Whitespace

Trailing whitespace MUST NOT be present after statements or serial comma break or on blank lines.

✖ Incorrect

var quotesExist = false;  

print_welcome_message();

↳ Incorrect because there are two spaces after var quotesExist = false;.

var myMovies = [
	'Slumdog Millionaire', 
	'Silver Linings Playbook', 
	'The Lives of Others', 
	'The Shawshank Redemption'
];

↳ Incorrect because there is a space after ,.

var quotesExist = false;
  
print_welcome_message();

↳ Incorrect because there are two spaces on the blank line below var quotesExist = false;.

✔ Correct

var quotesExist = false;

print_welcome_message();
var myMovies = [
	'Slumdog Millionaire',
	'Silver Linings Playbook',
	'The Lives of Others',
	'The Shawshank Redemption'
];

Formatting

7. Keywords

Keywords MUST be all lowercase.

✖ Incorrect

var isTrue = FALSE;
var isFalse = TRUE:
var movieQuote = NULL;

↳ Incorrect because FALSE, TRUE and NULL are not all lowercase.

✔ Correct

var isTrue = false;
var isFalse = true:
var movieQuote = null;

Formatting

8. Variables

Variables MUST start with a lowercase letter and subsequent words MUST start with uppercase letter.

✖ Incorrect

var welcome_Message = '';
var Welcome_Message = '';
var WELCOME_MESSAGE = '';

↳ Incorrect because var welcome_Message, var Welcome_Message and var WELCOME_MESSAGEare not camelcase.

var welcome_Message = '';

↳ Incorrect because welcome and message is separated with an underscore.

✔ Correct

var welcomeMessage = '';

Formatting

9. Global Variables

Global variables MUST be declared one variable per line and MUST be indented after the first. Global variables' use should be minimized. Variables should be scoped locally when possible. Global variables should be preceed by a comment that declares them as being global variables.

✖ Incorrect

var appConfig;var cache;var dbConnection;

↳ Incorrect because var appConfig, var cache and var dbConnection are together on one line.

↳ Incorrect because there is no comment preceeding the variables.

// global variables below
var appConfig;
    cache;
    dbConnection;

↳ Incorrect because cache and dbConnection don't have the keyword var.

✔ Correct

// global variables below
var appConfig;
var cache;
var dbConnection;

Formatting

10. Constants

Constants MUST be all uppercase and words MUST be separated by an underscore.

✖ Incorrect

var welcome_Message = '';
var Welcome_Message = '';
var welcome_message = '';

↳ Incorrect because var welcome_Message, var Welcome_Message and var welcome_message are not all uppercase.

var WELCOMEMESSAGE = '';

↳ Incorrect because WELCOME and MESSAGE are not separated with an underscore.

✔ Correct

var WELCOME_MESSAGE = '';

Formatting

11. Statements

Statements MUST be placed on their own line and MUST end with a semicolon.

✖ Incorrect

var quotesExist = false; print_welcome_message();

↳ Incorrect because var quotesExist = false; and print_welcome_message(); are on one line.

print_welcome_message()

↳ Incorrect because print_welcome_message() is missing a semicolon.

✔ Correct

var quotesExist = false;
print_welcome_message();

Formatting

12. Operators

Operators MUST be surrounded a space.

✖ Incorrect

var total=3+14;
var string='Hello, World! ';
var string.='Today is a good day!';

↳ Incorrect because there is no space surrounding the =, + or .= sign.

✔ Correct

var total = 3 + 14;
var string = 'Hello, World! ';
var string .= 'Today is a good day!';

Formatting

13. Unary Operators

Unary operators MUST be attached to their variable or integer.

✖ Incorrect

var index = 1;

index ++;
-- index;

↳ Incorrect because there is a space before ++ and after --.

✔ Correct

var index = 1;

index++;
--index;

Formatting

14. Concatenation Plus

Concatenation plus MUST be surrounded by a space.

✖ Incorrect

var date = new Date();
alert('Hello, World! Today is'+date+'!');

↳ Incorrect because there is no space surrounding +.

✔ Correct

var date = new Date();
alert('Hello, World! Today is ' + date + '!');

Formatting

15. Single Quotes

Single quotes MUST be used.

✖ Incorrect

alert("Hello, World!");

↳ Incorrect because "Hello, World!" is not written with single quotes.

✔ Correct

alert('Hello, World!');

Formatting

16. Double Quotes

Double quotes SHOULD NOT be used.

~ Acceptable

alert("Hello, World! He's watching movies and she's reading books.");

↳ Acceptable when long pieces of text have apostrophies that would need to be escaped.

✔ Preferred

var date = new Date();

alert('Hello, World! Today is ' + date + '!');

alert('Hello, World! He\'s watching movies and she\'s reading books.');

Formatting

7. Functions

This section describes the format for function names, calls, arguments and declarations.

  1. Function name MUST be all lowercase and words MUST be separated by an underscore
    • e.g. function welcome_message() {
  2. Function prefix MUST start with verb
    • e.g. get_, add_, update_, delete_, convert_, etc.
  3. Function call MUST NOT have a space between function name and open parenthesis
    • e.g. func();
  4. Function arguments
    • MUST NOT have a space before the comma
    • MUST have a space after the comma
    • MAY use line breaks for long arguments
    • MUST then place each argument on its own line
    • MUST then indent each argument once
    • MUST be ordered from required to optional first
    • MUST be ordered from high to low importance second
    • MUST use descriptive defaults
    • e.g. func(arg1, arg2 = 'asc', arg3 = 100);
  5. Function declaration MUST be documented using jsDoc tag style and SHOULD include
    • Short description
    • Optional long description, if needed
    • @author: Author name
    • @global: Global variables function uses, if applicable
    • @param: Parameters with data type, variable name, and description
    • @return: Return data type, if applicable
  6. Function return
    • MUST occur as early as possible
    • MUST be initialized prior at top
    • MUST be preceded by blank line, except inside control statement
    • i.e. if (!expr) { return false; }

Table of Contents

1. Function Name

Function name MUST be all lowercase and words MUST be separated by an underscore.

✖ Incorrect

get_Welcome_Message();
Get_Welcome_Message();
GET_WELCOME_MESSAGE();

↳ Incorrect because the function names are not all lowercase.

getwelcomemessage();

↳ Incorrect because get, welcome and message are not separated with an underscore.

✔ Correct

get_welcome_message();

Functions

2. Function Prefix

Function prefix MUST start with verb.

✖ Incorrect

active_users();
network_location(location1, location2);
widget_form(id);

↳ Incorrect because functions are not prefixed with a verb.

✔ Correct

get_active_users();
move_network_location(location1, location2);
delete_widget_form(id);

Functions

3. Function Call

Function call MUST NOT have a space between function name and open parenthesis.

✖ Incorrect

print_welcome_message ();

↳ Incorrect because there is a space between print_welcome_message and ().

✔ Correct

print_welcome_message();

Functions

4. Function Arguments

Function arguments:

  • MUST NOT have a space before the comma
  • MUST have a space after the comma
  • MAY use line breaks for long arguments
  • MUST then place each argument on its own line
  • MUST then indent each argument once
  • MUST be ordered from required to optional first
  • MUST be ordered from high to low importance second
  • MUST use descriptive defaults

✖ Incorrect

my_function(arg1 , arg2 , arg3);

↳ Incorrect because there is a space before ,.

my_function(arg1,arg2,arg3);

↳ Incorrect because there is no space after ,.

my_other_function(arg1_with_a_really_long_name,
	arg2_also_has_a_long_name,
	arg3
);

↳ Incorrect because arg1_with_a_really_long_name is not on its own line.

my_other_function(
arg1_with_a_really_long_name,
arg2_also_has_a_long_name,
arg3
);

↳ Incorrect because arguments are not indented once.

function get_objects(type, order = 'asc', limit) {
	// ...
}

↳ Incorrect because type, order and limit are not in order of required to optional.

function get_objects(limit, order, type) {
	// ...
}

↳ Incorrect because limit, order and type are not in order of importance.

function get_objects(type, order = true, limit = 100) {
	// ...
}

↳ Incorrect because true is not a descriptive default for order.

✔ Correct

my_function(arg1, arg2, arg3);

my_other_function(
	arg1_with_a_really_long_name,
	arg2_also_has_a_long_name,
	arg3
);

function get_objects(type, order = 'asc', limit = 100) {
	// ...
}

function add_users_to_office(array users, Office office) {
	// ...
}

Functions

5. Function Declaration

Function declaration MUST be documented using jsDoc tag style and SHOULD include:

  • Short description
  • Optional long description, if needed
  • @author: Author name
  • @global: Global variables function uses, if applicable
  • @param: Parameters with data type, variable name, and description
  • @return: Return data type, if applicable

✖ Incorrect

function my_function(id, type, width, height) {
	// ...
	
	return Photo;
}

↳ Incorrect because my_function is not documented.

✔ Correct

/**
 * Get photo from blog author
 * 
 * Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut id volutpat 
 * orci. Etiam pharetra eget turpis non ultrices. Pellentesque vitae risus 
 * sagittis, vehicula massa eget, tincidunt ligula.
 *
 * @author Firstname Lastname
 * @global var post
 * @param int id Author ID
 * @param string type Type of photo
 * @param int width Photo width in px
 * @param int height Photo height in px
 * @return object Photo
 */
function my_function(id, type, width, height) {
	// ...

	return Photo;
}

Functions

6. Function Return

Function return:

  • MUST occur as early as possible
  • MUST be initialized prior at top
  • MUST be preceded by blank line, except inside control statement

✖ Incorrect

function get_object() {
	var foo = false;
	if (expr1) {
		// ...
		if (expr2) {
			// ...
		}
	}

	return foo;
}

↳ Incorrect because get_object does not return as early as possible.

function get_movies() {
	// ...

	return movies;
}

↳ Incorrect because movies is not initialized at top.

function get_movies() {
	var movies = [];
	// ...
	
	return movies;
}

↳ Incorrect because return movies is not preceded by blank line.

✔ Correct

function get_object() {
	var foo = false;
	if (!expr1) {
		return foo;
	}
	if (!expr2) {
		return foo;
	}
	// ...

	return foo;
}
function get_movies() {
	var movies = [];
	// ...

	return movies;
}

Functions

8. Control Structures

This section defines the layout and usage of control structures. Note that this section is separated into rules that are applicable to all structures, followed by specific rules for individual structures.

  • Keyword MUST be followed by a space
    • e.g. if (, switch (, do {, for (
  • Opening parenthesis MUST NOT be followed by a space
    • e.g. (expr, (i
  • Closing parenthesis MUST NOT be preceded by a space
    • e.g. expr), i++), value)
  • Opening brace MUST be preceded by a space and MUST be followed by a new line
    • e.g. expr) {, i++) {
  • Structure body MUST be indented once and MUST be enclosed with curly braces (no shorthand)
    • e.g. if (expr) { ... }
  • Closing brace MUST start on the next line
    • i.e. ... }
  • Nesting MUST NOT exceed three levels
    • e.g. no if (expr1) { if (expr2) { if (expr3) { if (expr4) { ... }}}}

In addition to the rules above, some control structures have additional requirements:

  1. If, Else if, Else
    • elseif MUST be used instead of else if
    • elseif and else MUST be between } and { on one line
  2. Switch, Case
    • Case statement MUST be indented once
      • i.e. case 1:
    • Case body MUST be indented twice
      • i.e. func();
    • Break keyword MUST be indented twice
      • i.e. break;
    • Case logic MUST be separated by one blank line
      • i.e. case 1: ... break; case 2: ... break;
  3. While, Do While
  4. For, Each
  5. Try, Catch

Table of Contents

1. If, Else if, Else

  • else if MUST be used instead of elseif as elseif is invalid in jQuery
  • else if and else MUST be between } and { on one line

✖ Incorrect

	var expr1;
	var expr2;
	
	if (expr1) {
		// if body
	} elseif (expr2) {
		// elseif body
	} else {
		// else body
	}
	

↳ Incorrect because elseif was used instead of else if.

	var expr1 = false;
	var expr2 = true;
	
	if (expr1) {
		// if body
	}
	else if (expr2) {
		// else if body
	}
	else {
		// else body
	}
	

↳ Incorrect because else if and else are not between } and { on one line.

	var expr1   = '';
	var expr2   = '';
	var result2 = '';
	var result1 = if (expr1) ? true : false;
	
	if (expr2)
		result2 = true;
	

↳ Incorrect because structure body is not wrapped in curly braces.

✔ Correct

	var expr1;
	var expr2;
	var result1;
	var result2;
	
	if (expr1) {
		// if body
	} else if (expr2) {
		// else if body
	} else {
		// else body
	}
	
	if (expr1) {
		result1 = true;
	} else {
		result1 = false;
	}
	
	if (expr2) {
		result2 = true;
	}
	

Control Structures

2. Switch, Case

  • Case statement MUST be indented once
  • Case body MUST be indented twice
  • Break keyword MUST be indented twice
  • Case logic MUST be separated by one blank line

✖ Incorrect

	var expr;
	
	switch (expr) {
	case 0:
		echo 'First case, with a break';
		break;
	
	case 1:
		echo 'Second case, which falls through';
		// no break
	case 2:
	case 3:
	case 4:
		echo 'Third case, return instead of break';
		
		return;
	
	default:
		echo 'Default case';
		break;
	}
	

↳ Incorrect because case 0 thru default are not indented once.

	var expr;
	switch (expr) {
		case 0:
		echo 'First case, with a break';
		break;
	
		case 1:
		echo 'Second case, which falls through';
		// no break
		case 2:
		case 3:
		case 4:
		echo 'Third case, return instead of break';
		return;
	
		default:
		echo 'Default case';
		break;
	}
	
}

↳ Incorrect because echo, break and return are not indented twice.

	var expr;
	
	switch (expr) {
		case 0:
			echo 'First case, with a break';
			break;
		case 1:
			echo 'Second case, which falls through';
			// no break
		case 2:
		case 3:
		case 4:
			echo 'Third case, return instead of break';
			
			return;
		default:
			echo 'Default case';
			break;
	}
	

↳ Incorrect because case 0, case 1 thru case 4, and default are not separated by one blank line.

✔ Correct

	var expr;
	
	switch (expr) {
		case 0:
			echo 'First case, with a break';
			break;
	
		case 1:
			echo 'Second case, which falls through';
			// no break
		case 2:
		case 3:
		case 4:
			echo 'Third case, return instead of break';
			
			return;
	
		default:
			echo 'Default case';
			break;
	}
	

Control Structures

3. While, Do While

✔ Correct

	var expr

	while (expr) {
		// structure body
	}
	
	do {
		// structure body;
	} while (expr);
	

Control Structures

4. For, Each

✔ Correct

	for (i = 0; i < 10; i++) {
		// for body
	}
	
	$('.iterable').each(function(index) {
		// foreach body
	});
	

Control Structures

5. Try, Catch

✖ Incorrect

	try {
		// try body
	}
	catch (FirstExceptionType) {
		// catch body
	}
	catch (OtherExceptionType) {
		// catch body
	}
	

↳ Incorrect because catch is not between } and { on one line.

✔ Correct

	try {
		// try body
	} catch (FirstExceptionType) {
		// catch body
	} catch (OtherExceptionType) {
		// catch body
	}
	

Control Structures

9. Best Practices

  1. Variable initialization SHOULD occur prior to use and SHOULD occur early
    • e.g. var foo = '';, var bar = 0;
  2. Globals SHOULD NOT be used
    • i.e. no var myGlobal; outside of the scope of a function
  3. Objects, arrays SHOULD use literal notation
    • i.e var foo = [];, var bar = {};
  4. Explicit expressions SHOULD be used
    • e.g. if (expr === false), while (expr !== true)
  5. Event Handling SHOULD combine selector event handlers into a single declaration
    • e.g. jQuery('#listItem').on({ 'hover': function(){...},'click': function(){...} });
  6. Ajax SHOULD utilize promises
  7. Selectors SHOULD be consise and optimized for performance
    • i.e jQuery('#foo .bar').data();
  8. Performance Variables SHOULD be cached when possible
    • i.e. var foo = jQuery('#foo'); foo.attr('title', 'New Title');
  9. Code Groupings
    • Group code into functions for easy reuse and conditional loading

Table of Contents

1. Variable Initialization

Variable initialization SHOULD occur prior to use and SHOULD occur early.

~ Acceptable

var movies = get_movies();

↳ Acceptable, but movies should be initialized prior to use.

	if (expr) {
		// ....
	}
	
	var movies = [];
	movies = get_movies();
	

↳ Acceptable, but movies should be initialized earlier.

✔ Preferred

	var movies = [];
	
	if (expr) {
		// ....
	}
	
	movies = get_movies();
	

Best Practices

2. Globals

~ Acceptable

// global variables

var foo1 = true;
var foo2 = false;
var foo3  = 5;

console.log(foo3);

↳ Acceptable, but globals should be avoided if possible.

✔ Preferred

// global variables

function myFunc(){
  var foo1 = true;
  var foo2 = false;
  var foo3  = 5;

  return foo3;
}

console.log(myFunc());

↳ Acceptable, but globals should be avoided if possible.

Best Practices

3. Objects, Arrays

✖ Incorrect

var foo = new Array();
var bar = new Object();

✔ Correct

var foo = [];
var bar = {};

Best Practices

4. Explicit Expressions

Explicit expressions SHOULD be used.

~ Acceptable

if (expr == true) {
	// ...
}

↳ Acceptable, but === could be used here instead.

✔ Preferred

if (expr === true) {
	// ...
}

Best Practices

5. Event Handling

~ Acceptable

jQuery('#fooBar li').on('mouseenter', function() {
	jQuery(this).text('Click me!');
});

jQuery('#fooBar li').on('click', function() {
	jQuery(this).text('Why did you click me?!');
});

↳ Acceptable, but could be made more efficient by combining event handlers.

✔ Preferred

var listItems = jQuery('#longlist li');
listItems.on({
	'mouseenter': function() {
	jQuery(this).text('Click me!');
	},
    
	'click': function() {
	jQuery(this).text('Why did you click me?!');
	}

});

Best Practices

6. Ajax

~ Acceptable

function get_name(arg1) {
	var dynamicData = {};
	dynamicData['id'] = arg1;
	jQuery.ajax({
		url: 'get-name.php',
		type: 'get',
		data: dynamicData,
		success: function(data) {
	        	// Updates the UI based the ajax result
	        	var person = jQuery('#person');
	        	person.find('.person-name').text(data.name);  
	      	}
    });
}

get_name('2342342');
  

↳ Acceptable, but could be made more efficient and extensible by using promises.

✔ Preferred

function get_name(arg1) {
	var dynamicData = {};
	dynamicData['id'] = arg1;
    
	return jQuery.ajax({
		url: 'get-name.php',
		type: 'get',
		data: dynamicData
	});
}

get_name('2342342').done(function(data) {
	// Updates the UI based the ajax result
	var person = jQuery('#person');
	person.find('.person-name').text(data.name);  
});

Best Practices

7. Selectors

~ Acceptable

$('.foo').html();

$('#parent .foo').html();

↳ Acceptable, but will cause the entire DOM to be traversed. This is not efficient.

↳ Acceptable, as it will prevent the entire DOM from being searched, but is still not the fastest option.

✔ Preferred

var parent = $('#parent');
parent.find('.foo').html();

↳ Preferred, this is the fastest option and selector caching is utilized.

8. Performance

✖ Incorrect

jQuery('#elem').attr('title','This is a new title');
jQuery('#elem').css('color', 'red');
jQuery('#elem').fadeIn();

↳ Incorrect becasue jQuery('#elem') isn't cached and the methods called on that element aren't chained.

✔ Correct

// Stores the jQuery instance inside of a variable
var elem = jQuery('#elem');

// Set's an element's title attribute, color and fade it in with chaining
elem.attr('title', 'This is a new title')
	.css('color','red')
	.fadeIn();
  

Best Practices

9. Code Groupings

Store separate groupings of code as functions so that they can be conditionally called as well as re-initialized in callbacks or promises.

~ Acceptable

var elem = jQuery('#elem');
	
elem.attr('title','This is a new title');
elem.css('color', 'red');
elem.fadeIn();

✔ Preferred

function update_elements_text(){  
	var elem = jQuery('#elem');
	
	elem.attr('title','This is a new title');
	elem.css('color', 'red').fadeIn();
}  
update_elements_text();

Table of Contents

Inspired in part by code standards from:
idiomatic.js, Google Style Guide.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment