Skip to content
This repository has been archived by the owner on Dec 1, 2023. It is now read-only.

Coding standard for javascript

osj2507 edited this page Mar 16, 2013 · 1 revision

###Guidelines for Javascript & jQuery

  1. Use camelCase for naming javascript variables and functions.
  2. Use PascalCase for naming javascript "classes". It helps to show which functions that are instantiated with the 'new' operator.
  3. Never use Javascript for styling elements. Use it to add/remove CSS classes which are then styled in CSS. The only exception to this rule is for animation purposes.
  4. Never prepend an id with a tagName. E.g. don’t: $(“div#my-id”); - It’s bad for perfomance.
  5. Avoid explicit event handling in HTML. Do the binding of event handlers in the javascript file.
<!-- Bad -->
<span id=”my-span” onclick=”runMyFunction(); return false;”></span>
// Good
$("#my-span").on("click", function(){ 
    runMyFunction(); 
    return false; 
});
  1. Always cache jQuery objects/selections for later use.
// Bad - causes two DOM searches for the ".button" class
$(".button").toggle();
$("#form").append($(".button"));

// Good - keeps the DOM element in memory
var $buttons = $(.button”);
$buttons.toggle();
$("#form").append($buttons);
  1. Always declare variables with the var keyword or they will be defined in the global scope.
  2. Prepend variable names with $ if it holds a jQuery object.
var $mySpan = $("#my-span"); 
var review = $("review-body").val();
  1. Use $(window).load(function(){ … }); instead of $(document).ready(function(){ … }); when your code is not related to rendering the page. E.g. when binding click events.
  2. Use event delegation instead of event handling when possible. Especially when binding several events/handlers - It improves performance.
// Bad - loops all elements and does a bind for each
$(".all-my-buttons").bind("click", function(){ 
    $(this).hide();
});
// Good - Only binds one event, but delegates the handling. 
// Bonus - This handling also works if the buttons are created dynamically! Which won't work on a normal bind() method.
$("#button-wrapper").on("click", ".all-my-buttons", function(){ 
    $(this).hide();
});
  1. Declare variables on several lines.
// Bad
var a, b, c;

// Good
var a;
var b;
var c;