Sunday, April 29, 2012

Javascript Naming Conventions

These two articles give very good guidelines to Javascript naming conventions
http://javascript.crockford.com/code.html
http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml

This blog is to highlight some notes from these two guidelines:
  • File name: should use lowercase, end in .js, and should contain no punctuation except for - (dash) or _ (underscore) or . (dot)
  • Namespace: should be used to define one single global object for one library or one project, and nested object literal pattern is preferred
  • Naming: In general, use functionNamesLikeThis, variableNamesLikeThis, ClassNamesLikeThis, EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS
  • Access control: This pattern of public, private, and privileged members is possible because JavaScript has closures. Closure means that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned.
  • Variable: camelCase. Always define it using var, at the top of the function, and use of global variables should be minimized
  • Indentation: 4 spaces
  • Line length: 80 characters or 120 characters
  • Comment: Generally use line comments. Save block comments for formal documentation and for commenting out. Use JSDoc
  • Function: All functions should be declared before they are used. Constructor function uses ClassNamesLikeThis (PascalCase) instead of camelCase
  • Use {} instead of new Object(). Use [] instead of new Array()
  • Avoid the use of the comma operator except for very disciplined use in the control part of for statements. (This does not apply to the comma separator, which is used in object literals, array literals, var statements, and parameter lists)
  • In JavaScript blocks do not have scope
  • Avoid doing assignments in the condition part of if and while statements.
  • It is almost always better to use the === and !== operators.
  • Eval is evil. eval has aliases. Do not use the Function constructor. Do not pass strings to setTimeout or setInterval
  • Avoid the use of with
  • For consistency single-quotes (') are preferred to double-quotes ("). This is helpful when creating strings that include HTML
  • Pay attention to semicolon injection, so always add semicolon at the end
  • Compile JS and optimize JS

No comments:

Post a Comment