Skip to content

Latest commit

 

History

History
165 lines (146 loc) · 3.18 KB

File metadata and controls

165 lines (146 loc) · 3.18 KB

Dos and Donts in JavaScript

How to write good javascript code. Best practices for JavaScript coding.

be careful to use === or ==

avoid coding like "if(a='hi')" we should use

'hello' === varible or 'hello' == varible

instead

variblae === 'hello' or variblae == 'hello'

"for in" is not a good choice

remeber "for in" has bad performance then other loop statement, like for, while, do while.

Semicolon Insertion

use

return {
  status: true
};

instead

return
{
  status: true
};

use

if (boo) {
  //to do
}

instead

if (boo)
{
  //to do
}

length in for loop

use

for(var x=0, len = chocolatebars.length ; x < len; x++){
}

instead

for(var x=0; x < chocolatebars.length; x++){
}

If Boolean

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.

Basic “short circuting” with || (Logical OR)

To set default values, instead of this:

function documentTitle(theTitle) {
  if (!theTitle) {
    theTitle  = "Untitled Document";
  }
}

Use this:

function documentTitle(theTitle) {
  theTitle  = theTitle || "Untitled Document";
}

Block Scope

There is no block scope in js, we should declare variables at the beginning of function instead in the if statement or loop statement.

Don't put method in Constructor, defined methods in prototype.

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);
  }
}

Pass object as parameters instead one by one

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);

Set default value in prototype instead in controller

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';
  }
}

Thanks

Books

JavaScript: The Good Parts

Professional JavaScript for Web Developers

编写高质量代码:改善JavaScript程序的188个建议

Articles

12 Simple (Yet Powerful) JavaScript Tips

JavaScript language advanced Tips & Tricks

JavaScript and CSS guidelines for pragmatists

Some HTML, CSS and JS best practices