Building simple objects

Javascript objects are basically just hash tables, a group of related properties and functions that can be accessed by a key. Properties are dynamically added at runtime. Methods are just properties that happen to be functions.

Building a simple object

The simplest way to build objects in Javascript is by declaring a new variable of type object and assigning the properties or methods that the object needs:

  1. var rufus = new Object();
  2. rufus.name = "rufus";
  3. rufus.species = "cat";
  4. rufus.hello = function() { alert("miaow"); }

Complete example.

Javascript objects are dynamic. Their properties do not need to be defined before they are set. You can add a new property at any time at runtime just by assigning it. You do not need to declare data types like you do in class based languages like C# and java but you can share implementation between objects of the same type using constructor functions and object prototypes.

Notice that we have set the hello property of rufus to a function rather than a primitive data type like a string. This is possible because functions are just a special type of object in javascript. They can be treated just like a string or a number or any other data type. A javascript object’s methods are just a property that happen to be a function.

The hello function is also being declared as an anonymous function. We don’t need to declare it before we assign it to the property and it doesn’t have a name.

Dot syntax vs subscript syntax

Objects in javascript are just hashtables. There is nothing particularly special about them, they are just a collection of key/item pairs. One side effect of this is you can access their properties with either an object like dot syntax or a array like subscript syntax.

The previous example used the dot syntax to access the name, species and hello properties. Here’s the same example using the subscript syntax:

  1. var casper = new Object();
  2. casper["name"] = "casper";
  3. casper["species"] = "bird";
  4. casper["hello"] = function() { alert("squark! squark!");
  5. }

Complete example.

There is no difference between the two syntaxes. They are just two different ways of saying the same thing and can be used interchangeably.

The advantage of the dot syntax is it looks more natural to people used to accessing object properties in languages like C# or java. Most javascript code that uses objects accesses the properties in this way.

Sometimes subscript syntax can be very useful because the key is indexed with a string. The string can be built at runtime to access an object’s properties without knowing exactly what properties it has.

For example you could use a foreach loop to iterate through each property in the object or dynamically build the property name:

  1. for(var property in rufus)
  2.     alert(rufus[property].toString());
  3. var myObject = {
  4.     property1: "chocolate",
  5.     property2: "cake",
  6.     property3: "brownies"
  7. }
  8. for(var x=1; x<4; x++)
  9.     alert(myObject["property" + x]);

Complete example

Object literal syntax

In the first example we declared an object by calling the Object constructor function. There is a quicker (as in less typing) way to do this using something called the object literal.

The shortcut syntax object literal syntax is assigning the variable to a pair of braces. Assigning a variable to the object literal is exactly the same as calling the Object constructor:

  1. var empty1 = {}; // is the same as saying – but is quicker to type
  2. var empty2 = new Object();

The object literal can also be used to set up the object’s properties. The properties can be created as a list of key/value pairs. It’s very useful for when you want to initialize an object with a heap of different properties when you create it. It’s a very common thing to see in Javascript code.

Here’s the first example declared as an object literal:

  1. var sabby = {
  2.      name : "Sabby",
  3.      species: "cat",
  4.      hello : function() { alert("hissss"); }
  5. };

Complete example

There is absolutely no difference between objects created with any of these syntaxes. You should choose the one that works best for what you’re doing. Once you have declared an object using the object literal syntax that, you can still use the dot or subscript syntax to add or change its properties:

  1. sabby.age = 7;

When is this useful?

Creating simple objects like this is very useful for situations where you want to pass around group of related variables around a script.

Imagine a situation where you are using a library that supports custom events and you want to pass some information about your event to the function that is handling it. You could write ten lines of code to create a javascript object type that has all of the properties you need or you could write one line of code to create a simple object using object literal syntax. In most cases it will only make a difference in where the object is declared, it won’t make any difference to the code that’s using the object.

  1. this.fireEvent({element: navigationElement, state : "active" });
  2. function onNavigationStateChange(e){
  3.     // do something here
  4.     alert(e.element.id + " is " + e.state);
  5. }

Another thing that the simple objects (particularly the object literal) is useful for is creating a set of related library functions. This is the same sort of situation where you might create a class full of static functions in C#.

Here’s an example of what an array helper library might look like:

  1. var ArrayUtil = {
  2.     contains : function(array, element)
  3.     {
  4.         for(var x=0; x<array .length; x++)
  5.         {
  6.             if(array[x] == element)
  7.                return true;
  8.         }
  9.         return false;
  10.     },
  11.     exclude : function(list, items)
  12.     {
  13.         …
  14.     },
  15.     makeList : function(list)
  16.     {
  17.         …
  18.     }
  19. }
  20. var list = ["A", "B", "C"];
  21. alert("Has A? " + ArrayUtil.contains(list, "A"));

Complete example.

What’s next?

Javascript functions are first class objects. They are just a special type of object which means you can do anything with them that you could do with any other type of object. This is important to understand when creating objects in javascript because object methods are just properties that happen to be functions.

This article is part of a set of related posts about How javascript objects work.

Posted on 17 Aug 08 by Helen Emerson (last updated on 29 Nov 09).
Filed under Javascript