Categories

Javascript Best Practices

Posted on: June 8, 2014 by Dimitar Ivanov

Avoid globals

Global variables are visible in every scope. They can be changed by any part of your program at any time. Avoiding global variables in early stage will save you a lot of problems when your code base grows up.

<script type="text/javascript">
//AVOID
var x = 5; //it's global
window.y = 2; //it's global
//it's global
function multiply(x, y) {
    return x * y;
}
//BETTER
(function () {
    var x = 5, y = 2;
    function multiply(x, y) {
        return x * y;
    }
})();
</script>

Avoid multiple "var" statements

Declare var only once. You can place your var statements everywhere in your program, but it's more readable if your put them at the top of your functions or block scope. Don't forget to declare your variables and functions before use them.

<script type="text/javascript">
//AVOID
var price = 45;
var delivery = 12;
function getTax(sum) {
    var rate1 = 10;
    var rate2 = 20;
    if (sum > 100) {
        var tax = (sum * rate1) / 100;
    } else {
        var tax = (sum * rate2) / 100;
    }
    return tax;
}
var sum = price + delivery;
var tax = getTax(sum);

//BETTER
var sum, tax,
    price = 45, 
    delivery = 12;

function getTax(sum) {
    var tax,
        rate1 = 10, rate2 = 20;
    if (sum > 100) {
        tax = (sum * rate1) / 100;
    } else {
        tax = (sum * rate2) / 100;
    }
    return tax;
}

sum = price + delivery;
tax = getTax(sum);
</script>

Use === instead of ==

Always use === and !== operators because they are reliable. Using their similars == and != may lead to unpredictable results.

<script type="text/javascript">
//AVOID
false == '0' //true
//BETTER
false === '0' //false
</script>

Avoid using "eval"

Due possible security vulnerabilities you should avoid using eval function.

Avoid using "with" statement

Using the with statement may lead to unpredictable results.

Use semicolons

Javascript will try to insert automatically semicolons if you missed out. But you should not relies on this.

Avoid increment(++) and decrement(--) operators

Due possible security vulnerabilities you should avoid increment and decrement operators.

<script type="text/javascript">
//AVOID
for (var i = 0; i < 10; i++)
//BETTER
for (var i = 0; i < 10; i += 1)
</script>

The proper way for iterate over objects

Before using an object property you should check if it exists. So you need to use the hasOwnProperty method.

<script type="text/javascript">
var store = {'lemon': 8, 'banana': 12, 'orange': 3};
//WRONG
for (var x in store) {
    console.log(x, store[x]);
}
//BETTER
for (var x in store) {
    if (store.hasOwnProperty(x)) {
        console.log(x, store[x]);
    }
}
</script>

Optimize Loops

Instead of reading the length of an array at every iteration, you should get it only once.

<script type="text/javascript">
var haystack = [1,10,13,7,29,0,4,21];
//AVOID
for (var i = 0; i < haystack.length; i += 1) {
    console.log(haystack[i]);
}
//BETTER
for (var i = 0, iCnt = haystack.length; i < iCnt; i += 1) {
    console.log(haystack[i]);
}
</script>

Stop touching the DOM

Accessing the DOM is memory expensive and may slow down your javascript program. So it's always better to cache the references to DOM elements.

<script type="text/javascript">
//AVOID
document.getElementById("test").style.display = 'block';
document.getElementById("test").className = 'my-class';
document.getElementById("test").innerHTML = 'Hello World';
//BETTER
var el = document.getElementById("test");
el.style.display = 'block';
el.className = 'my-class';
el.innerHTML = 'Hello World';
</script>

String concatenation

You can concatenate strings in many ways, but most efficient is Array.join()

<script type="text/javascript">
var store = {'lemon': 'yellow', 'cherry': 'red'};
//AVOID
var str = "Lemons are " + store.lemon + ", tomatos are" + store.cherry;
//BETTER
var str = ["Lemons are ", store.lemon, ", tomatos are", store.cherry].join("");
</script>
Conclusion

There are great free tools on the market that can help you to validate, analyze and improve your javascript code. Check out one of the best JSLint and JSHint. There are also a bunch of plugins for your favorite IDE (Eclipse, NetBeans, WebStorm, etc.).

See also
Social sharing

If you have questions about javascript best practices, please leave a comment below. Thanks for reading.


1 Comment

Dimitar Ivanov
Dimitar Ivanov May 6, 2015 at 03:44 am
More tips are on their way.

Comments are closed