Javascript

Writing JavaScript Clean Code And Best Practices

How to write clean code in javascript, why i should write clean code in javascript. In this tutorial i will show some guidelines of JavaScript best practices. You should write your code so that it is easy to understand. Ambiguity, thus, should be avoided at all cost. Do this only to clarify your code as there is no need to have a life story in the comments.

 

Use of Global Variables Should Be Minimized

Use namespaces for your code to organize it into modules and to avoid code collisions. Optimal number of global variables introduced is zero and if this is not an option then stick to one. Encapsulate your code inside anonymous function and execute the function immediately:

(function(){
    // Do stuff here
}());

Use Single “var” Declaration per Scope

Since “var” accepts multiple declarations there is no reason to use more. All scope variables are moved to the top of the scope anyway (this is called hoisting). This may help reduce potential unexpected behavior in case duplicate names are introduced or some other logical mistakes are made.

(function(){

    var firstName = 'John',
        lastName = 'Doe',
        fullName = firstName + ' ' + lastName;
        
    // The rest of the function body
    
}());

Use Strict

As we already know before ECMAScript 5 you can use a variable without declaring it this would create it in a global scope:

(function(){
    name = 'John';
}());

With “use strict” you would just get an error:

(function(){
    'use strict';
    name = 'John';
}());

It helps you avoid introducing global variables inadvertently and spot errors early.

Module Pattern

Try to always to use a single namespace for your application so the following code block is bad because it will cause code collision in the:

function do_something()
{
  // code block
}

function do_something2()
{
  // code block
}

function do_something3()
{
  // code block
}

But this code is clean:

var App = (function () {
    'use strict';
    
    var settings;
    
    return {
    
        init: function(initialSettings){
            settings = initialSettings;
        },
        
        getVersion: function (){
            return settings.version;
        }
        
    };
}());

Keep code organized in modules. Augment application by attaching modules to it:

// Search module:
(function (app) {

    var module = {};
    
    module.find = function (query) {
        // Perform search
    };
    
    module.verifyQuery = function (query) {
        // Ver
    };
    
    // More module methods go here
    
    app.search = module;

}(App));

Don’t write functions that do everything. Write small functions that perform specific tasks rather than catch-all “smart” functions.

Development Code is for Developers

Do not write code for yourself. Write it for other developers who will take it over from you.

Prefer Clarity over Brevity. That means that function and variable naming should be meaningful rather than short. JavaScript compressor (Closure Compiler, YUI Compressor) will minify it for you if you end up with really long names. These rules apply to many other languages, too. The same goes the other way: things that work well in other languages may work well in JavaScript, too.

Log as much as you can. You may see logs in the console when you least expect them. It will help you have a better understanding what is going on, especially if the system is complex. This is very useful for other developer who will maintain the code in the future. Console can be a big time saver when trying to locate needed line of script or sometimes just to be aware what code is being executed. In Google Chrome it shows file and line from which it was called, too.

Be aware that code may brake if console is not present. To avoid errors replace it with fake console object and methods, when console is not present:

var console = window.console || {};
console.log = console.log || function(){};
console.warn = console.warn || function(){};
console.error = console.error || function(){};
console.info = console.info || function(){};

This is of course not necessary in the production code. Stripping this code can be built in into the build process, so that logging code is removed before compression and deployment to production. Following regex will strip all calls to console:

^\s*console\.(log|warn|error|info)\(.+\);\s*$

Visual Event is a bookmarklet which provides debugging information about events that have been attached to DOM elements. It can be big time saver when trying to locate what code is being called when an event is triggered.

Development code is for developers, production code is for machines. Therefore minimize and optimize code for production. Use build process to minify, optimize and combine code files.

Allow for Configuration

This includes labels, CSS classes, CSS namespaces, ID’s and etc. By having configuration objects we make maintenance a breeze. That also opens many opportunities for customizations.

Optimize

Optimize your code. It’s hard to come up with simplest solution right off the bat, so when refining your code look what you can remove or how can you simplify it.

You can create DOM elements in the loop but avoid inserting them into DOM. Keep DOM changes to the minimum. Avoid HTML creation in JavaScript as it’s hard to keep track of the quality that is produced. Use prebuilt templates and keep templates where it’s easy to maintain them.

0 0 votes
Article Rating

What's your reaction?

Excited
0
Happy
0
Not Sure
0
Confused
0

You may also like

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments