- Angular
- ECMAScript 6
- JSON (and JavaScript object literal notation)
Note: This style guide inherits rules from the C-Based Languages Style Guide, and the Global Style Guide.
- Class members (e.g., properties, functions) and namespaces should be
camelCase
(e.g.,doSomething()
) - Use
_this
as the variable name when saving a reference tothis
(although.bind()
for scoping is preferred)
- Always end lines with semicolons; do not rely on implicit insertion (source)
- Use single quotes for string values, not double quotes; this helps avoid the need for escaping
- Only access properties using subscript notation (i.e.,
[]
) when the property name is variable - Use
===
and!==
over==
and!=
as these are more precise and predictable - Name functions to aid in debugging (i.e., so functions are identified in stack traces)
- Always set
use strict
- Always declare variables using
var
(enforced inuse strict
) - Namespaces should be used when possible, using either library features or an object wrapper
- Do not use
eval()
or Internet Explorer's conditional comments (e.g.,/*@cc_on ... @*/
) - Do not use
for in
loops for arrays (source) - Do not use wrapper objects for primitive types (e.g.,
var isVisible = new Boolean(true)
); implicit casting is fine (e.g.,var isVisible = true
) - When possible, use JavaScript's boolean expression shortcut (e.g.,
if (variable) {}
as opposed toif (variable === true) {}
) (source) - Use the literal syntax for creating objects (e.g.,
{}
notnew Object()
) and arrays (e.g.,[]
notnew Array()
) - Assign methods to the prototype object, instead of overwriting the prototype with a new object
- Use proper feature detection instead of relying on user agents; use of Modernizr is encouraged
- Prefer loading third-party libraries from CDNs; this can decrease page load times by relying on caching
- Generate source maps during compilation and minification to simplify debugging
Note: The guidance for several of the above rules change with ECMAScript 6; please refer to the ECMAScript 6 Style Guide for details.
Note: See the JSON Style Guide for guidance specific to JavaScript object notation (JSON), JavaScript object literal notation, and array literal notation.
- Use JSDoc-style comments to allow for optional generation of documentation
- Always define documentation for classes; properties; methods, their parameters, and return type
- If namespaces are used (e.g., with framework modules) use
namespace
andmemberOf
to provide documentation
/**
* FILE TITLE
* @namespace namespace
* @desc Description
* @param {string} Parameter description
* @return {number} Return description
*/
- Declaring one variable per
var
v. multiple variables - Use of accessor functions for properties