How to write good javascript code. Best practices for JavaScript coding.
avoid coding like "if(a='hi')" we should use
'hello' === varible or 'hello' == varibleinstead
variblae === 'hello' or variblae == 'hello'remeber "for in" has bad performance then other loop statement, like for, while, do while.
use
return {
status: true
};instead
return
{
status: true
};use
if (boo) {
//to do
}instead
if (boo)
{
//to do
}use
for(var x=0, len = chocolatebars.length ; x < len; x++){
}instead
for(var x=0; x < chocolatebars.length; x++){
}if we want to validate a property whether in a project, we should now use
if (person.age) {
}we should use
if (person.hasOwnProperty('age')) {
}Reason: if statement return true, if the value is object, not empty string, not zero number, or ture. Return false, when the value is null, undefined, 0, false, NaN or empty string.
To set default values, instead of this:
function documentTitle(theTitle) {
if (!theTitle) {
theTitle = "Untitled Document";
}
}Use this:
function documentTitle(theTitle) {
theTitle = theTitle || "Untitled Document";
}There is no block scope in js, we should declare variables at the beginning of function instead in the if statement or loop statement.
use
function Person(name){
this.name = name;
}
Person.prototype.sayHi = function () {
alert('Hello ' + this.name);
}instead
function Person(name){
this.name = name;
this.sayHi = function () {
alert('Hello ' + this.name);
}
}If we pass object as parameters, it will be not necessary to consider the parameter order, and we can pass some must parameters and set some pameter as default value.
Do
var myObject = maker({
first: f,
middle: m,
last: l,
state: s,
city: c
});Dont
var myObject = maker(f, l, m, c, s);use
function Car(t) {
if(t) {
this.type = t;
}
}
Car.prototype.type = 'gasoline';instead
function Car(t) {
if(t) {
this.type = t;
} else {
this.type = 'gasoline';
}
}JavaScript: The Good Parts
Professional JavaScript for Web Developers
编写高质量代码:改善JavaScript程序的188个建议
12 Simple (Yet Powerful) JavaScript Tips
JavaScript language advanced Tips & Tricks