When writing any programming code, different developers will have different opinions. But it’s always good to refer to it, and here are the 14 best JS code writing tips from Javascript Toolbox , translated by Sofish ( 1 , 2 ).
1. Always use 'var'
In JavaScript, variables are either globally scoped or function scoped, and using the "var" keyword will be the key to keeping variables concise and clear. When declaring a variable that is either global or function-level, always prepend the "var" keyword. The following example will highlight the potential problems of not doing this.
Problems 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!
Because the variable i in the variable function does not use var to make it a function-level variable, in this example it refers to a global variable. It is a common practice to always use var to declare global variables, but it is crucial to use var to define a function-scope variable. The following two methods are functionally equivalent:
correct function
function test() {
var i=0;
for (i=0; i<10; i++) {
alert("Hello World!");
}
}
correct function
function test() {
for (var i=0; i<10; i++) {
alert("Hello World!");
}
}
2. Feature detection rather than browser detection
Some code is written to discover the browser version and perform different actions on it based on the client the user is using. This, in general, is a very bad practice. A better approach is to use feature detection. Before using an advanced feature that older browsers may not support, first check whether (the browser) has this function or feature, and then use it. It's better to detect the browser version alone, even if you know its performance. You can find an in-depth article discussing this issue at http://www.jibbering.com/faq/faq_notes/not_browser_detect.html .
example:
if (document.getElementById) {
var element = document.getElementById('MyId');
}
else {
alert('Your browser lacks the capabilities required to run this script!');
}
Source: Happy Favorites