DJ Quilter

Front-End Developer

A Beginners Guide to Javascript Objects

In my time using Javascript I’ve used Javascript Objects in three ways that I can think of. The first is the one that you will see in the vast majority of tutorials relating to Javascript Objects. The second is almost never seen in tutorials (I found one example in getting ready to write this article) but is, I feel, far more useful to me as a developer. There’s a third, which was not nearly as mind-blowing as the second, but is still useful.

This Standard-Javascript-Object-Tutorial Type of Object

Generally I would expect this to be used in game development or maybe in an application to manage user data. I won’t go into too much detail (others have done this to death):

// Creates an Object with a property.
function Character() {
  this.hitpoints = 10;
}

// Sets up an method and assigns it to our Object.
Character.prototype.action = function() {
  return 'Boom!';
}

// Creates a character using our Object as a basis.
var dave = new Character();
// Makes our character do something.
dave.action();

In case you haven’t seen this before, an Object will have properties, which are just variables, and methods which are functions. The prototype allows you to create a method which is related specifically to your Object.

More in-depth explanations of all of this can be found on MDN:

Although, I would suggest this use of an Object is not useful for the majority of scripts that you might write, it is probably useful for larger applications, and is also a good way of getting your head around the way in which Objects work.

The Super-Useful Type of Object

This is something which I was shown by a colleague in the last year, and was a bit of a revelation for me, providing me with a way of using Objects on a daily basis that has made my Javascript better:

// Name our Object.
var namespace = {
  // Set some properties for our Object.
  someProperty: 1,
  anotherProperty: true,

  // Create a method for initializing all of our other methods (conditionally if you need to).
  init: function() {
    if(namespace.anotherProperty == true){
      namespace.theMethod();
    }
  }

  // Set up the rest of the methods that we need.
  theMethod: function() {
    namespace.someProperty === 2;
    return namespace.someProperty;
  }
}

// Run our ‘initializing’ method.
$(document).ready(namespace.init());

Everything is activated through the namespaces’ ‘init’ function which is called at the bottom of the script, once the DOM is ready for action.

Once you’ve run the ‘init’ method, the namespace code is run in its own little bubble (which, incidentally, is called a namespace), keeping it separate from all of the other Javascript that is running on the page.

Notice that, other than when they are set, all properties and functions are referenced via dot notation (ie namespace.thePropertyOrMethodName). If you don’t remember to do this, you’ll find your script fairly unresponsive, which is the only real downside I can see to using Objects in this way.

In terms of upsides though, we have the following:

  • Namespacing – Putting your Javascript in a namespace Object prevents other scripts and libraries from messing with your properties and methods (for example, if they had the same name).
  • Organisation – I find that this approach helps me keep my code much more organised. If you’re working on larger sites/applications which use a lot of Javascript, you could extend this by using multiple namespaces. This would keep different pieces of functionality separate from one another structurally, but would still allow them to call on each others properties and methods should you need them to (although, strictly speaking, I think this is called the Module Pattern).
  • Performance – You might not want some parts of your script running on all pages of your site every time you go to a new page. It might be a bit of a performance drag or, worst case, might cause unwanted errors. If that’s the case, you can set conditions within your ‘initializing’ method, so that your methods only run when you want them to.

If those aren’t enough for you, I don’t know what more I can do to convince you, ‘cos those are some pretty good benefits!

The Third Type of Object (Not Quite As Amazing As The Last One, But Still Pretty Good)

You can also use Objects to create associative arrays. This means an array that is accessed via a keyword rather than a number. Check out the below example:

// Set up your Object.
var superheroId = new Object;

// Define your Object’s properties.
superheroId.batman = 'Bruce';
superheroId['superman'] = 'Clark';

// Print the info in your console.
console.log(superheroId.batman);
console.log(superheroId['superman']);

You can access and set your properties via dot.notation (as in superId.batman) or bracket notation (as in superId[‘superman’]).