Use !== instead of !=
Prefer the following syntax for if.
if (condition) {
statements;
}
rather than
if (condition)
statement;
Use eval() only if absolutely required. (subject to review)
Function naming
Functions that are intended to be used with “new” should be given names with initial “capital letters” and names with initial capital letters should be used only with constructor functions that take the new prefix.
Use Global variables with care. Incorrect use may result in weird behaviors.
Remove unreachable code as you may not get any warnings.
Fastest string concatenation (will explain more about this)
var arr = ['item 1', 'item 2', 'item 3', ...];
var list = '
- ' + arr.join('
- ') + '
Don’t pass a string to “SetInterval” or “SetTimeOut” function.
Don’t use the “With” statement. For e.g.
with (customer.name) {
firstName = “rajesh”;
lastName = “p”;
}
Instead use the var syntax if applicable.
var o = customer.name;
o.firstName = “rajesh”;
o.lastName = “p”;
Use {} instead of New Object()
There are multiple way to create objects in js. For e.g.
var o = new Object();
o.firstName = “rajesh”;
o.lastName = “p”;
o.printName = function() {
console.log(this.name);
}
Instead use the below approach…
var o = {
firstName: “Rajesh”,
lastName: “P”,
printName: function() {
console.log(this.name);
}
}
NOTE: To simple create an empty object use
var o = {};
Use[] instead of New Array()
The same applies for creating a new array.
var a = [“Rajesh”, “Developer”]; instead of var a = new Array(); a[0] = “Rajesh”; and so on..
Always use semicolon(;) ;
Optimize loops
for e.g. Change the below code from
var names = [“Cool”, “Dude”];
for (var i = 0; I < names.length; i++) { // Don’t access the length property in the loop. Take it outside as shown below.
callSomeFunction(names[i]);
}
To
var names = [“Cool”, “Dude”];
var all = names.length;
for (var i = 0; I < all; i++) {
callSomeFunction(names[i]);
}
No comments:
Post a Comment