JavaScript Better Practices

This is from a post called ASP.NET AJAX Best Priactices on CodeProject, but after reading it I’ve rather call it as titled. Here is the general summary on this very very nice article:

  • Use “var” whenever a variable is to be declared
  • Reduce scopes (Try avoiding nesting, functions or loops)
  • Use less DOM element concatenation – concatenate everything into string first, then assign to the DOM element
  • Don’t write your own method while there is one by the framework already
  • Avoid string concatenation, use Array instead – “push” each pieces of the string into array and then use “join” to get the complete string
  • Introduce function delegate
    This one is worth mentioning. When calling a function in a loop, delegate before the loop because JavaScript interpreter will use the function then as local variable and will not lookup in its scope china for the function body in each iteration
    Code: var delegate = processElement; // processElement is the function
    delegate(element1);
  • Introduct DOM elements and function caching
    Similar to function delegation. Example:
    var divContentAppendChild = $get(‘divContent’).appendChild;
    for (var i = 0; i < count; i++)
    divContentAppendChild(element[i]);
  • Avoid using switch if possible, as JavaScript interpreter can’t optimize switch block.

By Bryan Xu