JavaScript is all about objects.

When thinking about JavaScript objects, simply think about groups of key-values pairs (these are sometimes known as “associate arrays” “hash tables” or “hash maps” in other languages). An object literal is a list of zero or more pairs of property names and associated values of an object.

The syntax

  • Wrap the object in curly brace { }
  • Separate property name from value with a colon
  • Separate each property name-value pair with a comma

Example:

// Declare object
     var Robot = {
           name : "pinocchio",
           model : "wood",
           powerOn   : function () {
             // code here
           }
    }

    // Access properties
    Robot.name; // pinocchio
    Robot.['model']; // wood

    // Calling function
    Robot.powerOn();

The benefits of using object literal

  • Encapsulate related code Encapsulation (or grouping) of related code helps prevent clashes between variable or function names. This means we can have the function powerOn() for our Robot Object above, and a separate powerOn() function for a different Object.
  • Minimize the use of global variables Global variables can be accessed and set from any piece of JavaScript. Again, by avoiding this you can prevent clashes with other similarly named variables.
  • Eliminate anonymous functions Anonymous functions can be useful sometimes for short scripts, but can’t easily be re-used or unit tested and are difficult to debug. When you see a JavaScript error in the console and the stack trace just says “anonymous function” it’s difficult to know where to start!
  • Easy to debug Because all related code is together and most functions are named, debugging code becomes a far simpler job – you know where to look in your code straight away when you have a problem.
  • Increase reusability and portability Named functions can be called from multiple places. For example, the Robot.powerOn() function above could be assigned to a number of different click events on a webpage. If you need to change the behaviour of the function, you only have to do it in one place. A well written object can be taken from one JavaScript application and re-used in another with no changes.

Let’s take a closer look

Say you want to display matching content after a list item is clicked, while hiding the content from all list items.

You might write the following script….

$(function() {
    $( "#myFeature li" ).append( "div" ).on('click',function() {
        var item = $( this );
        var div = item.find( "div" );
        div.load( "foo.php?item=" + item.attr( "id" ), function() {
            div.show();
            item.siblings().find( "div" ).hide();
        });
    });
  });

But really, it should look like this…

var myFeature = {
    config : {
        items : '#myFeature li',
        container : 'div',
        urlBase : 'foo.php?item='
    },

    init : function(config) {
        // Allow overriding the default config
        $.extend(myFeature.config, config);

        $(myFeature.config.items)
            .each(myFeature.getContent)
            .on('click', function() {
                myFeature.showContent;
            });
    },

    buildUrl : function() {
        myFeature.currentItem = $(this);
        return myFeature.config.urlBase + myFeature.currentItem.attr('id');
    },

    getContent : function(callback) {
        var url = myFeature.buildUrl();
        myFeature.config.load(url, callback);
    },

    showContent : function() {
        myFeature.currentItem.find('div').show();
        myFeature.hideContent(myFeature.currentItem.siblings());
    },

    hideContent : function($elements) {
        $elements.find('div').hide();
    }
  };

  $(function() {
        myFeature.init();
  });

You’ll probably notice that this is longer than the original code and might think it’s overkill. But actually it’s not; there’s a lot of value in the additional lines!

By breaking things down and grouping code into small blocks, it is

  • easier to access and
  • It is much easier to read well named functions and understand what is happening. The short version is actually more complex to read.
  • more logical
  • easy to extend
  • Testing is much easier – each short function can be tested on it’s own.
  • easy to copy and move to other application. The whole object can be re-used elsewhere just by modifying the config variables.

Conclusion

I hope the example above helps give you a better understanding of the object literal notation and how it helps you with developing more complex features. The logic behind it should help you think through the elements and break down behaviours to code blocks that are simple, yet together perform complex functions. Additionally, it builds a solid foundation for extending and reusing the code.

Jessie Wang, Senior frontend developer

Written by Jessie W.

“I have no special talent, I am only passionately curious.“— Albert Einstein

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s