20091November

Object Literal Notation: What's Up With That?

This article is intended for people familiar with computer programming.

Some languages support a feature called object literal notation. JavaScript is one such language.

Statements such as: x = 5; or name = "Shawn"; are common in programming. The part on the right (5 or "Shawn") is called a literal. (Technically, the literal is Shawn and the quotes are metadata which tell the interpreter or compiler what its type is.) The first is an integer literal; the second is a string literal. In some respects, it is like a constant. 5 is always 5: you can’t change its value. Unlike a constant, a literal’s value is immediately obvious upon reading it - its name is its value. Such is true in an object literal.

Here is an example of an object definition in JavaScript:

var person = new Object(); person.name = "Shawn"; person.addFriend = function(friend) { //add a person as a friend }
This example does not use object literal notation. It creates a basic object, then modifies it by adding properties and methods. Sometimes it’s useful just to define the object instead of to create one and modify it several times. This is done with object literal notation.

var person = { name: "Shawn", addFriend: function(friend) { //add a person as a friend } }
Note that everything after the equals is a literal. Since the literal is of type object, it is an object literal.

Tagged: and