+1

Javascript Good Practices

Javascript is on the way to become an important part of every web application as well as the most misunderstanding language in the IT world. This post isn't gonna to go in detail of making the application better but just some minor customs from my experience to improve each line of code.

1. When Use === And ==

JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing. But == operators is better in case we want to compare invalid value.

For example, we have an variable a what can be null or undefined :

Bad

a === undefined
=> true  (if a is undefined)
=> false (if a is null)

Better

a == undefined
=> true (always)

a == undefined <=> a === undefined || a === null

2. Best Case To Use typeof

Well, of course typeof is a method to get type of variable, but the following case I like to use it most:

Bad

a == undefined
=> Uncaught ReferenceError: a is not defined()

Better

typeof a == 'undefined'
=> true

The fact is sometimes, you really don't know exactly a variable is declared or not, defined or not, using typeof is the best choice. We can write in another way like this window.a == undefined but it ins't cool such as the first one, right?

3. Declare Variables Outside of the For Statement

When executing lengthy "for" statements, don't make the engine work any harder than it must.

Bad

for (i = 1; i < arr1000.length; i ++ ) {
	var ship = document.getElementById('ship');
	ship.style.top = i + 'px';
}

Better

var ship = document.getElementById('ship');
for (i = 1; i < arr1000.length; i ++ ) {
	ship.style.top = i + 'px';
}

Even better

var ship = document.getElementById('ship');
var array_length = arr1000.length;
for (i = 1; i < array_length; i ++ ) {
	ship.style.top = i + 'px';
}

4. Reduce Global Variables

By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries.

Bad

var company_name = 'Framgia';
var number_of_staff = 500;
var location = 'Hanoi';

function sendMail(company){...};
sendMail(company_name);

Better

var BigCompany = {
	name: 'Framgia',
    staff_no: 500,
    location: 'Hanoi'
};
...
sendMail(BigCompany.name);

5. Deal With Long List of Variables

Bad

var aPerson = 'Alex';
var anotherPerson = 'Tom';
var oneMorePerson = 'Gordon';

Better

var someItem    = 'Alex',
    anotherItem = 'Tom',
    oneMoreItem = 'Gordon';

...Should be rather self-explanatory. It seems th real speed improvements here, but it cleans up your code a bit.

6. Remember To Use Semicolons

In fact that, most of browsers and many cases we can omit semi-colons:

var person = 'Alex'
function doSomething() {
  sayHi(person)
}

But I can say that this is really a bad practice because it can cause some serious or harder to find bug in future when you combine or uglified chunks of code. It's paint to spend hours to find out the errors made from a missing semi-colon. Always write like this

var person = 'Alex';
function doSomething() {
  sayHi(person);
}

7. Self-Executing Functions

There're many times you have to write a JS function just one-time using and you still wrap that chunnk of code inside a beautiful function with beautiful name.

function startADay() {
	brushTeeth();
    washFace();
    dressing();
    goToWork();
}

//go throught thousand lines of code ...
startAday();

Rather than calling a function, it's quite simple to make a function run automatically when a page loads, or a parent function is called

(function startADay() {
	brushTeeth();
    washFace();
    dressing();
    goToWork();
})();

8. Raw JavaScript Can Always Be Quicker Than Using a Library

JavaScript libraries, such as jQuery and Angular, can save you an enormous amount of time when coding -- especially with AJAX operations. Having said that, always keep in mind that a library can never be as fast as raw JavaScript (assuming you code correctly).

jQuery's "each" method is great for looping, but using a native "for" statement will always be an ounce quicker.

9. Use Closure Is Not Good Idea

I must heard about closure in Javascript, strong and powerfuld and dozen of other fancy words. It really helps us to be able to write code like this

var oneItem = 'table';

function wreckingBall(){
  oneItem = 'broken';
}

wreckingBall();
console.log(oneItem);
=> 'broken'

Well, we don't need to remember to declear oneItem inside the function, VM(Virtual Machine) will automatically look up outside of function's scope when no oneItem is there and yeah, it found a oneItem then. The problem is what if oneItem is a global variable and the function was places under many many levels of scope (inside many other functions), apparently, VM has to look up many times to find out that variable. Futhermore, the file with thousand lines of code, at the first glance at this function, nobody has any idea where oneTime came from. Since a lot of time consumed to check and read code again, the below is much better:

var oneItem = 'table';

function wreckingBall(target){
  target = 'broken';
}

wreckingBall(oneItem);

The same result but the faster and better performance I sure.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí