JavaScript DOs and DONTs
1. Use Shortcut Notations:
This code [Avoid]
Is the same as [Use Instead]
var lunch = new Array();
lunch[0]=’Dosa’;
lunch[1]=’Roti’;
lunch[2]=’Rice’;
lunch[3]=’what the heck is this?’;
var lunch = [
‘Dosa’,
‘Roti’,
‘Rice’,
‘what the heck is this?’
];
if(v){
var x = v;
} else {
var x =10;
}
var x = v || 10;
var direction;
if(x > 100){
direction = 1;
} else {
direction = -1;
}
var direction = (x > 100)
? 1 : –1;
2. Avoid Globals:
Reason: You run the danger of your code being overwritten by
any other JavaScript added to the page after yours.
Workaround: use closures and the module pattern.
Problem: all variables are global and can be accessed; access
is not contained, anything in the page can overwrite what you do.
var current = null;var labels = { ‘home’:‘home’, ‘articles’:‘articles’, ‘contact’:‘contact’ };function init(){};function show(){ current = 1;};function hide(){ show();};
Object Literal: Everything is contained
but can be accessed via the object name
Problem: Repetition of module name leads to huge code and is
annoying.
demo = {
current:null,
labels:{
‘home’:’home’,
‘articles’:’articles’,
‘contact’:’contact’
},
init:function(){
},
show:function(){
demo.current = 1;
},
hide:function(){
demo.show();
}
}
Module Pattern: You need to specify what is global and what isnt –
switching syntax in between.
Problem: Repetition of module name, different syntax for
inner functions.
module = function(){
var labels = {
‘home’:’home’,
‘articles’:’articles’,
‘contact’:’contact’
};
return {
current:null,
init:function(){
},
show:function(){
module.current = 1;
},
hide:function(){
module.show();
}
}
}();
Revealing
Module Pattern: Keep consistent syntax and mix and match what to make global.
module = function(){ var current = null; var labels = { ‘home’:‘home’, ‘articles’:‘articles’, ‘contact’:‘contact’ }; var init = function(){ }; var show = function(){ current = 1; }; var hide = function(){ show(); } return{init:init, show:show, current:current}}();module.init();