Skip to main content

Lite 's Library tagged tips   View Popular

17 Jan 09

Javascript Best Practices

Introduction

This document is a list of best practices and preferred ways of developing javascript code, based on opinions and experience from many developers in the javascript community. Since this is a list of recommendations rather than a list of absolute rules, experienced developers may have slightly differing opinions from those expressed below.

Table Of Contents

1. Always Use 'var'
2. Feature-Detect Rather Than Browser-Detect
3. Use Square Bracket Notation
4. Avoid 'eval'
5. Reference Forms and Form Elements Correctly
6. Avoid 'with' Statements
7. Use onclick In Anchors Instead Of javascript: Pseudo-Protocol
8. Use The Unary + Operator To TypeConvert To Number
9. Avoid document.all
10. Don't Use HTML Comments In Script Blocks
11. Avoid Cluttering The Global Namespace
12. Avoid sync "Ajax" calls
13. Use JSON
14. Use Correct <script> Tags

Always Use 'var'

Variables in javascript either have global scope or function scope, and using the 'var' keyword is vital to keeping them straight. When declaring a variable for use either as a global variable or as a function-level variable, always prefix the declaration with the 'var' keyword. The example below highlights the potential problem caused by not doing so.
Problem Caused By Not Using Var

var i=0; // This is good - creates a global variable
function test() {
for (i=0; i<10; i++) {
alert("Hello World!");
}
}
test();
alert(i); // The global variable i is now 10!

Since the variable i inside the function was not declared as a function-level variable by using the 'var' keyword, it references the global variable in this example. It is a good idea to always declare global variables using 'var', but it is vital to declare function-scoped variables using 'var'. The two approaches below are functionally identical.
Fixed Function

function test() {
var i=0;
for (i=0; i<10; i++) {
alert("Hello World!");
}
}

Fixed Function

function test() {
for (var i=0; i<10; i++) {
alert("Hello World!");
}

www.javascripttoolbox.com/bestpractices - Preview

javascript practices tips for-supermemo

1 - 20 of 44 Next › Last »
Showing 20 items per page

Diigo is about better ways to research, share and collaborate on information. Learn more »

Join Diigo