Professional Documents
Culture Documents
Javascript (Jquery) Style Guide Javascript (Jquery) Style Guide
Javascript (Jquery) Style Guide 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.
Icon Legend:
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
Filename
▲ 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.
jQuery(document).ready(function($) {
// your code
});
// EOF
// your code
// EOF
▲ Table of Contents
3. jQuery Initialization
▲ Table of Contents
1. Document Ready
✖ 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
$(function() {
// your code //
});
// EOF
▲ jQuery Initialization
4. Namespaces
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.
↳ Incorrect because var FooBar = FooBar || {}; is not followed by a blank line.
✔ Correct
console.log('js-enabled');
▲ Namespaces
2. Namespace Name
Namespace name MUST start with a capital letter and MUST be camelcase.
✖ Incorrect
✔ Correct
▲ Namespaces
5. Comments
This section describes how comments should be formatted and used.
▲ Table of Contents
1. Single-line Comments
✖ Incorrect
jQuery(document).ready(function($) {
/* This is a comment */
});
✔ Correct
jQuery(document).ready(function($) {
// This is a comment
});
// EOF
▲ Comments
2. Multi-line Comments
✖ Incorrect
jQuery(document).ready(function($) {
// This is a
// multi-line
// comment
});
// EOF
✔ Correct
jQuery(document).ready(function($) {
/**
* This is a
* multi-line
* comment
*/
});
// EOF
▲ Comments
3. Comments
✖ Incorrect
jQuery(document).ready(function($) {
});
// EOF
✔ Correct
jQuery(document).ready(function($) {
});
// EOF
▲ Comments
4. Blocks of Code
~ Acceptable
var users = ['John', 'Jane', 'Jim'];
✔ 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'];
▲ Comments
5. Ambiguous Numbers
✖ Incorrect
✔ Correct
// Script times out after 1,000 records
while (expr && x < 1000) {
// ...
}
▲ Comments
6. External Variables
✖ Incorrect
// ...
✔ Correct
// ...
// _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.
▲ Table of Contents
1. Line Length
✖ Incorrect
if ( jQuery.inArray('Slumdog Millionaire', movies) !== -1 && jQuery.inArray('Silver Linings Playbook', movies)!== -1 && jQuery.inArra
// if body
}
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 c
↳ 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'
];
if (hasAllMovies) {
// if body
}
▲ Formatting
2. Line Indentation
✖ Incorrect
function print_welcome_message() {
alert('WELCOME_MESSAGE');
}
});
✔ Correct
function print_welcome_message() {
alert('WELCOME_MESSAGE');
}
▲ Formatting
3. Blank Lines
~ 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
}
✔ Preferred
var myMovies = [
'Slumdog Millionaire',
'Silver Linings Playbook',
'The Lives of Others',
'The Shawshank Redemption'
];
if (hasAllMovies) {
// if body
}
▲ Formatting
4. Text Alignment
✖ 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 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
✖ Incorrect
jQuery('#movies').find('.movie').highlight().end().find('.selected').updateCount();
✔ 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
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'
];
print_welcome_message();
↳ Incorrect because there are two spaces on the blank line below var quotesExist = false; .
✔ Correct
print_welcome_message();
var myMovies = [
'Slumdog Millionaire',
'Silver Linings Playbook',
'The Lives of Others',
'The Shawshank Redemption'
];
▲ Formatting
7. Keywords
✖ Incorrect
↳ Incorrect because FALSE , TRUE and NULL are not all lowercase.
✔ Correct
▲ 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_MESSAGE are not camelcase.
✔ Correct
▲ 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
↳ Incorrect because var appConfig , var cache and var dbConnection are together on one line.
↳ Incorrect because cache and dbConnection don't have the keyword var .
✔ Correct
▲ Formatting
10. Constants
✖ Incorrect
↳ 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
▲ Formatting
11. Statements
Statements MUST be placed on their own line and MUST end with a semicolon.
✖ Incorrect
↳ Incorrect because var quotesExist = false; and print_welcome_message(); are on one line.
print_welcome_message()
✔ Correct
▲ Formatting
12. Operators
✖ Incorrect
var total=3+14;
var string='Hello, World! ';
var string.='Today is a good day!';
✔ Correct
▲ Formatting
var index = 1;
index ++;
-- index;
✔ Correct
var index = 1;
index++;
--index;
▲ Formatting
✖ Incorrect
✔ Correct
▲ Formatting
✖ Incorrect
alert("Hello, World!");
✔ Correct
alert('Hello, World!');
▲ Formatting
~ 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
▲ 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();
getwelcomemessage();
↳ Incorrect because get , welcome and message are not separated with an underscore.
✔ Correct
get_welcome_message();
▲ Functions
2. Function Prefix
✖ Incorrect
active_users();
network_location(location1, location2);
widget_form(id);
✔ 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 ();
✔ Correct
print_welcome_message();
▲ Functions
4. Function Arguments
Function arguments:
✖ Incorrect
my_other_function(arg1_with_a_really_long_name,
arg2_also_has_a_long_name,
arg3
);
my_other_function(
arg1_with_a_really_long_name,
arg2_also_has_a_long_name,
arg3
);
↳ Incorrect because type , order and limit are not in order of required to optional.
↳ Incorrect because limit , order and type are not in order of importance.
✔ Correct
my_other_function(
arg1_with_a_really_long_name,
arg2_also_has_a_long_name,
arg3
);
▲ 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
return Photo;
}
✔ 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:
✖ Incorrect
function get_object() {
var foo = false;
if (expr1) {
// ...
if (expr2) {
// ...
}
}
return foo;
}
function get_movies() {
// ...
return movies;
}
function get_movies() {
var movies = [];
// ...
return movies;
}
✔ 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.
In addition to the rules above, some control structures have additional requirements:
▲ Table of Contents
✖ Incorrect
var expr1;
var expr2;
if (expr1) {
// if body
} elseif (expr2) {
// elseif body
} else {
// else body
}
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.
if (expr2)
result2 = true;
✔ 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
✖ 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;
}
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
$('.iterable').each(function(index) {
// foreach body
});
▲ Control Structures
5. Try, Catch
✖ Incorrect
try {
// try body
}
catch (FirstExceptionType) {
// catch body
}
catch (OtherExceptionType) {
// catch body
}
✔ 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
if (expr) {
// ....
}
✔ Preferred
if (expr) {
// ....
}
movies = get_movies();
▲ Best Practices
2. Globals
~ Acceptable
// global variables
console.log(foo3);
✔ Preferred
// global variables
function myFunc(){
var foo1 = true;
var foo2 = false;
var foo3 = 5;
return foo3;
}
console.log(myFunc());
▲ Best Practices
3. Objects, Arrays
✖ Incorrect
✔ Correct
▲ Best Practices
4. Explicit Expressions
~ Acceptable
if (expr == true) {
// ...
}
✔ Preferred
▲ Best Practices
5. Event Handling
~ Acceptable
jQuery('#fooBar li').on('mouseenter', function() {
jQuery(this).text('Click me!');
});
✔ Preferred
'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
8. Performance
✖ Incorrect
↳ Incorrect becasue jQuery('#elem') isn't cached and the methods called on that element aren't chained.
✔ Correct
▲ 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
✔ Preferred
function update_elements_text(){
var elem = jQuery('#elem');
▲ Table of Contents