Lite 's Library tagged → View Popular
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!");
}
20 Websites That Made Me A Better Web Developer | Six Revisions : Web Development and Design
Selected Tags
Related Tags
Sponsored Links
Top Contributors
Groups interested in tips
-
how to decorate your home
sites of nicely-decorated h...
Items: 30 | Visits: 254
Created by: Iris Deters
-
Need learn and unread
Items: 12 | Visits: 169
Created by: Vincent Tsao
-
Firefox
Items: 4 | Visits: 208
Created by: Daniel Gauthier
Diigo is about better ways to research, share and collaborate on information. Learn more »
Join Diigo
