Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Ajax

JavaScript Maintenance Tips

5.00/5 (1 vote)
23 Jul 2013CPOL3 min read 10.6K  
Javascript coding tips

Introduction

This tip is a continuation to my earlier one on JavaScript performance that can be found here. Tips mentioned in both these articles go hand in hand and front end developers, especially beginners, should be aware of these nitty gritty details. The intended audience for this tip is JavaScript beginners with a few years of programming experience. 

Background  

JavaScript nowadays is found in majority of the web apps hosted on the Internet. One common observation in most of these applications is that the way people code JavaScript more often than not causes maintenance nightmares! It either isn't object oriented enough or the code isn't structured well! Often, developers either overlook or are ignorant about JavaScript coding practices. The intent of this tip is not to provide developers with a laundry list of check points. There are lots of websites out there on the Internet which provide those details. The idea behind writing this tip is to simply capture often repeated bad practices and provide some tips on how to correct them so that when your code goes into maintenance, people don't curse you. ;) So hopefully this tip and the performance tips should provide developers with atleast some basic insight on how to start writing maintainable, high performing code.  

Tips on Maintainability

  1. Avoid writing global functions. The below code should be avoided if possible:
  2. JavaScript
    //MyScript.js
    
    function doSomeThing() {
      
    }
    //....More functions like above 
    
    //....Still more global functions!!!
    function doSomeThingElse() {
      
    }

    The issue with global functions is that they are all appended to window namespace. In case another script file uses the same function name, the function in the script that’s loaded last will execute causing unexpected behavior.

  3. Try to structure your code into namespaces. For example, developers can create object literals to wrap their functions and create a logical grouping. If you have coded in Java or C#, you will appreciate this concept.
  4. JavaScript
    var MyApp = { };
    
    MyApp.Utilities = {
        doSomething : function(){
       
        },
        doSomethingElse : function(){ 
                    
        } 
    };

    Tip: As a best practice, try to use camel case for your function names and Pascal case for namespaces and classes.

  5. Use the Module pattern if possible. For example, you can always wrap your functionality around a self-executing function that creates a closure and also manages the scope appropriately.
  6. JavaScript
    var MyApp = { };
    
    MyApp.Utilities = (function() {
        this.c1 = ""; //public variable
        var c2 = ""; //private variable
       
        //private function
        function doSomething() {
           
        }
     
        return { 
                 //public function
            doSomeThingElse: function() {
                //Logic
                doSomething();
            }
        }; 
    })();
  7. JavaScript engine always inserts a semi colon at the end of the statement in case we forget it. So if(something){ is equivalent to if(something){;. Hence it's always best practice to have curly braces in the same line for conditionals and loops.
  8. JavaScript
    //Recommended
    if (something) {
       
    }
    for (i = 0; i < 10; i += 1) {
       
    }
      
    //Not recommended - consumes space unless minified
    if (something)
    {   
    }

    Note: We shouldn’t take the JS Engine for granted and skip semi colons always. Do not forget to include semicolon at the end of function expression but you can skip semicolon at the end of function declarations.

  9. Avoid using the built in functions when initializing arrays. This is because unless the right arguments are passed to the constructor, your code can backfire.
  10. JavaScript
    var m = new Array(1);//This is Ok 
    
    var n = new Array(1.5);//Not Ok

    To avoid this, it's best to use the literal notation to initialize an array.

    JavaScript
    var n = [1, 1.5];//Simple and easy!

    Similarly, avoid using built-ins for Boolean.

    JavaScript
     var b = new Boolean(0);//b is true since we are using new
    
    var b = Boolean(0);//b is false since we are evaluating the expression
  11. Always specify radix whenever you use parse* functions (parseInt, parseFloat, etc.). Specifying the radix makes the code readable and reduces the probability of unexpected behavior.
  12. JavaScript
    parseInt("9", 10);//gives 9
    
    parseInt("9", 8);//gives NaN
    
    parseInt("10", 8);//gives 8
  13. Always use typeof when you aren't sure about the kind of object you are working with!
  14. JavaScript
    function foo(g){
      if(typeof g === 'function'){
      //Do your stuff.. 
      }
    }

Parting Note

If you find this tip useful, please share it with the developer community. 

Happy learning. :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)