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:
- Overview of all rules with a quick example
- Each rule called out with examples of do's and don'ts
Icon Legend:
·
Space, ⇥
Tab, ↵
Enter/Return
- Files
- Skeleton
- jQuery Initialization
- Namespaces
- Comments
- Formatting
- Functions
- Control Structures
- Best Practices
This section describes the format and naming convention of jQuery files.
- Character encoding MUST be set to UTF-8 without BOM
- Sublime.app →
File
›Save with Encoding
›UTF-8
- Sublime.app →
- Line endings MUST be set to Unix (LF)
- Sublime.app →
View
›Line Endings
›Unix
- Sublime.app →
- Letters MUST be all lowercase
- e.g.
foo.js
- e.g.
- Words MUST be separated with a hyphen
- e.g.
foo-bar.js
- e.g.
- Version SHOULD be used if this is a js file that will be updated frequently
- e.g.
foo-bar-1.4.2.js
- e.g.
- Minified MUST be appended to the filename if the js file is minified
- e.g.
foo-bar-1.4.2.min.js
- e.g.
- Plugins SHOULD be prefixed with jquery
- e.g.
jquery.foo.js
- e.g.
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.
- 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
- 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
This section describes the initialization of the jQuery environment.
- Document Ready MUST be initialized in noConflict mode
- i.e.
jQuery(document).ready(function($) {
↵
↵
...
- i.e.
jQuery document ready must be initialized in noConflict mode
$(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.
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
This section describes how to use a namespace in javascript.
- Namespace declaration MUST be the first statement and MUST be followed by a blank line
- i.e.
var MyNamespace = MyNamespace || {};
- i.e.
- Namespace name MUST start with a capital letter and MUST be camelcase
- e.g.
var MyFooBar = MyFooBar || {};
- e.g.
Namespace declaration MUST be the first statement and MUST be followed by a blank line.
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.
var FooBar = FooBar || {};
var BarFoo = BarFoo || {};
console.log('js-enabled');
↳ Multiple namespace example.
Namespace name MUST start with a capital letter and MUST be camelcase.
var foobar = fooBar || {};
↳ Incorrect because fooBar
does not start with a capital letter.
var FOOBAR = FOOBAR || {};
↳ Incorrect because FOOBAR
is not written in camelcase.
var FooBar = FooBar || {};
This section describes how comments should be formatted and used.
- Single-line comments MUST use a forward slashes
- e.g.
// My comment
- e.g.
- Multi-line comments MUST use the block format
- i.e.
/**
↵
* My comment
↵
*/
- i.e.
- Comments MUST be on their own line
- i.e.
↵
// My comment
- i.e.
- Blocks of code SHOULD be explained or summarized
- e.g.
// Compare user accounts from export against expired accounts in system
- e.g.
- Ambiguous numbers MUST be clarified
- e.g.
// 1,000 processable records per hour API limit
- e.g.
- External variables MUST be clarified
- e.g.
// Global variable defined via wp_localize_script in functions.php
- e.g.
Single-line comments MUST use forward slashes.
jQuery(document).ready(function($) {
/* This is a comment */
});
↳ Incorrect because it uses /*
and */
for a single-line comment.
jQuery(document).ready(function($) {
// This is a comment
});
// EOF
▲ Comments
Multi-line comments MUST use the block format.
jQuery(document).ready(function($) {
// This is a
// multi-line
// comment
});
// EOF
↳ Incorrect because it uses //
for a multi-line comment.
jQuery(document).ready(function($) {
/**
* This is a
* multi-line
* comment
*/
});
// EOF
▲ Comments
Comment MUST be on their own line.
jQuery(document).ready(function($) {
print_welcome_message(); // Prints welcome message
});
// EOF
↳ Incorrect because // Prints welcome message
is not on its own line.
jQuery(document).ready(function($) {
// Prints welcome message
print_welcome_message();
});
// EOF
▲ Comments
Blocks of code SHOULD be explained or summarized.
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.
/**
* 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
Ambiguous numbers MUST be clarified.
while (expr && x < 1000) {
// ...
}
↳ Incorrect because 1000
is not clarified.
// Script times out after 1,000 records
while (expr && x < 1000) {
// ...
}
▲ Comments
External variables MUST be clarified.
var users = _wpcf7.cache;
// ...
jQuery.each(users, function(index, user) {
// ...
});
↳ Incorrect because source of users
is not clear.
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
This section outline various, general formatting rules related to whitespace and text.
- Line length MUST NOT exceed 80 characters, unless it is text
- i.e.
|---- 80+ chars ----|
→ refactor expression and/or break list values
- i.e.
- Line indentation MUST be accomplished using tabs
- i.e.
function func() {
↵
⇥
...
↵
}
- i.e.
- Blank lines SHOULD be added between logical blocks of code
- i.e.
...
↵
↵
...
- i.e.
- Text alignment MUST be accomplished using spaces
- i.e.
var foo
·
·
·
= ...;
- i.e.
- Method chaining MUST indent when making long method chains
- e.g.
$('#foo .bar')
↵
⇥
.hide()
↵``.css('opacity', .9)
↵
.show();
- e.g.
- Trailing whitespace MUST NOT be present after statements or serial comma break or on blank lines
- i.e. no
...
·
·
↵
·
↵
...
- i.e. no
- Keywords MUST be all lowercase
- e.g.
false
,true
,null
, etc.
- e.g.
- Variables MUST start first word lowercase and subsequent words MUST start with uppercase letter
- e.g.
var welcomeMessage;
- e.g.
- 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;
- e.g.
- Constants MUST be all uppercase and words MUST be separated by an underscore
- e.g.
WELCOME_MESSAGE
- e.g.
- Statements MUST be placed on their own line and MUST end with a semicolon
- e.g.
welcome_message();
- e.g.
- Operators MUST be surrounded by a space
- e.g.
var total = 15 + 7;
,foo .= '';
- e.g.
- Unary operators MUST be attached to their variable or integer
- e.g.
index++
,--index
- e.g.
- Concatenation plus MUST be surrounded by a space
- e.g.
alert('Read:' + welcomeMessage);
- e.g.
- Single quotes MUST be used
- e.g.
alert('Hello, World!');
- e.g.
- Double quotes SHOULD NOT be used
- e.g.
alert('Read: ' + welcomeMessage);
- e.g.
Line length MUST NOT exceed 80 characters, unless it is text.
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.
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.
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'
);
Line indentation MUST be accomplished using tabs.
function print_welcome_message() {
alert('WELCOME_MESSAGE');
}
});
↳ Incorrect because spaces are used to indent alert('WELCOME_MESSAGE');
instead of a tab.
function print_welcome_message() {
alert('WELCOME_MESSAGE');
}
Blank lines SHOULD be added between logical blocks of code.
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.
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
}
Text alignment MUST be accomplished using spaces.
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.
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.'
];
Long method chains MUST be indented.
jQuery('#movies').find('.movie').highlight().end().find('.selected').updateCount();
↳ Incorrect because methods are on a single line and not indented.
jQuery('#movies')
.find('.movie')
.highlight()
.end()
.find('.selected')
.updateCount();
Trailing whitespace MUST NOT be present after statements or serial comma break or on blank lines.
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;
.
var quotesExist = false;
print_welcome_message();
var myMovies = [
'Slumdog Millionaire',
'Silver Linings Playbook',
'The Lives of Others',
'The Shawshank Redemption'
];
Keywords MUST be all lowercase.
var isTrue = FALSE;
var isFalse = TRUE:
var movieQuote = NULL;
↳ Incorrect because FALSE
, TRUE
and NULL
are not all lowercase.
var isTrue = false;
var isFalse = true:
var movieQuote = null;
Variables MUST start with a lowercase letter and subsequent words MUST start with uppercase letter.
var welcome_Message = '';
var Welcome_Message = '';
var WELCOME_MESSAGE = '';
↳ Incorrect because var welcome_Message
, var Welcome_Message
and var WELCOME_MESSAGE
are not camelcase.
var welcome_Message = '';
↳ Incorrect because welcome
and message
is separated with an underscore.
var welcomeMessage = '';
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.
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
.
// global variables below
var appConfig;
var cache;
var dbConnection;
Constants MUST be all uppercase and words MUST be separated by an underscore.
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.
var WELCOME_MESSAGE = '';
Statements MUST be placed on their own line and MUST end with a semicolon.
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.
var quotesExist = false;
print_welcome_message();
Operators MUST be surrounded a space.
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.
var total = 3 + 14;
var string = 'Hello, World! ';
var string .= 'Today is a good day!';
Unary operators MUST be attached to their variable or integer.
var index = 1;
index ++;
-- index;
↳ Incorrect because there is a space before ++
and after --
.
var index = 1;
index++;
--index;
Concatenation plus MUST be surrounded by a space.
var date = new Date();
alert('Hello, World! Today is'+date+'!');
↳ Incorrect because there is no space surrounding +
.
var date = new Date();
alert('Hello, World! Today is ' + date + '!');
Single quotes MUST be used.
alert("Hello, World!");
↳ Incorrect because "Hello, World!"
is not written with single quotes.
alert('Hello, World!');
Double quotes SHOULD NOT be used.
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.
var date = new Date();
alert('Hello, World! Today is ' + date + '!');
alert('Hello, World! He\'s watching movies and she\'s reading books.');
This section describes the format for function names, calls, arguments and declarations.
- Function name MUST be all lowercase and words MUST be separated by an underscore
- e.g.
function welcome_message() {
- e.g.
- Function prefix MUST start with verb
- e.g.
get_
,add_
,update_
,delete_
,convert_
, etc.
- e.g.
- Function call MUST NOT have a space between function name and open parenthesis
- e.g.
func();
- e.g.
- 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);
- 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
- 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; }
Function name MUST be all lowercase and words MUST be separated by an underscore.
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.
get_welcome_message();
Function prefix MUST start with verb.
active_users();
network_location(location1, location2);
widget_form(id);
↳ Incorrect because functions are not prefixed with a verb.
get_active_users();
move_network_location(location1, location2);
delete_widget_form(id);
Function call MUST NOT have a space between function name and open parenthesis.
print_welcome_message ();
↳ Incorrect because there is a space between print_welcome_message
and ()
.
print_welcome_message();
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
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
.
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) {
// ...
}
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
function my_function(id, type, width, height) {
// ...
return Photo;
}
↳ Incorrect because my_function
is not documented.
/**
* 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;
}
Function return:
- MUST occur as early as possible
- MUST be initialized prior at top
- MUST be preceded by blank line, except inside control statement
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.
function get_object() {
var foo = false;
if (!expr1) {
return foo;
}
if (!expr2) {
return foo;
}
// ...
return foo;
}
function get_movies() {
var movies = [];
// ...
return movies;
}
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 (
- e.g.
- Opening parenthesis MUST NOT be followed by a space
- e.g.
(expr
,(i
- e.g.
- Closing parenthesis MUST NOT be preceded by a space
- e.g.
expr)
,i++)
,value)
- e.g.
- Opening brace MUST be preceded by a space and MUST be followed by a new line
- e.g.
expr) {
,i++) {
- e.g.
- Structure body MUST be indented once and MUST be enclosed with curly braces (no shorthand)
- e.g.
if (expr) {
↵
⇥
...
↵
}
- e.g.
- Closing brace MUST start on the next line
- i.e.
...
↵
}
- i.e.
- Nesting MUST NOT exceed three levels
- e.g. no
if (expr1) { if (expr2) { if (expr3) { if (expr4) {
...
}}}}
- e.g. no
In addition to the rules above, some control structures have additional requirements:
- If, Else if, Else
elseif
MUST be used instead ofelse if
elseif
andelse
MUST be between}
and{
on one line
- Switch, Case
- Case statement MUST be indented once
- i.e.
⇥
case 1:
- i.e.
- Case body MUST be indented twice
- i.e.
⇥
⇥
func();
- i.e.
- Break keyword MUST be indented twice
- i.e.
⇥
⇥
break;
- i.e.
- Case logic MUST be separated by one blank line
- i.e.
case 1: ... break;
↵
↵
case 2: ... break;
- i.e.
- Case statement MUST be indented once
- While, Do While
- For, Each
- Try, Catch
- Avoid using Try/catch in javascript as it may affect browser performance negatively
catch
MUST be between}
and{
on one line
else if
MUST be used instead ofelseif
aselseif
is invalid in jQueryelse if
andelse
MUST be between}
and{
on one line
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.
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;
}
- 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
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.
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
while (expr) {
// structure body
}
do {
// structure body;
} while (expr);
for (i = 0; i < 10; i++) {
// for body
}
$('.iterable').each(function(index) {
// foreach body
});
try {
// try body
}
catch (FirstExceptionType) {
// catch body
}
catch (OtherExceptionType) {
// catch body
}
↳ Incorrect because catch
is not between }
and {
on one line.
try {
// try body
} catch (FirstExceptionType) {
// catch body
} catch (OtherExceptionType) {
// catch body
}
- Variable initialization SHOULD occur prior to use and SHOULD occur early
- e.g.
var foo = '';
,var bar = 0;
- e.g.
- Globals SHOULD NOT be used
- i.e. no
var myGlobal;
outside of the scope of a function
- i.e. no
- Objects, arrays SHOULD use literal notation
- i.e
var foo = [];
,var bar = {};
- i.e
- Explicit expressions SHOULD be used
- e.g.
if (expr === false)
,while (expr !== true)
- e.g.
- Event Handling SHOULD combine selector event handlers into a single declaration
- e.g.
jQuery('#listItem').on({ 'hover': function(){...},'click': function(){...} });
- e.g.
- Ajax SHOULD utilize promises
- Selectors SHOULD be consise and optimized for performance
- i.e
jQuery('#foo .bar').data();
- i.e
- Performance Variables SHOULD be cached when possible
- i.e.
var foo = jQuery('#foo');
↵
foo.attr('title', 'New Title');
- i.e.
- Code Groupings
- Group code into functions for easy reuse and conditional loading
Variable initialization SHOULD occur prior to use and SHOULD occur early.
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.
var movies = [];
if (expr) {
// ....
}
movies = get_movies();
// global variables
var foo1 = true;
var foo2 = false;
var foo3 = 5;
console.log(foo3);
↳ Acceptable, but globals should be avoided if possible.
// 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.
var foo = new Array();
var bar = new Object();
var foo = [];
var bar = {};
Explicit expressions SHOULD be used.
if (expr == true) {
// ...
}
↳ Acceptable, but ===
could be used here instead.
if (expr === true) {
// ...
}
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.
var listItems = jQuery('#longlist li');
listItems.on({
'mouseenter': function() {
jQuery(this).text('Click me!');
},
'click': function() {
jQuery(this).text('Why did you click me?!');
}
});
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.
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);
});
$('.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.
var parent = $('#parent');
parent.find('.foo').html();
↳ Preferred, this is the fastest option and selector caching is utilized.
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.
// 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();
Store separate groupings of code as functions so that they can be conditionally called as well as re-initialized in callbacks or promises.
var elem = jQuery('#elem');
elem.attr('title','This is a new title');
elem.css('color', 'red');
elem.fadeIn();
function update_elements_text(){
var elem = jQuery('#elem');
elem.attr('title','This is a new title');
elem.css('color', 'red').fadeIn();
}
update_elements_text();
Inspired in part by code standards from:
idiomatic.js, Google Style Guide.