JavaScript Object Literal

An object literal is a comma separated list of name value pairs wrapped in curly braces. In JavaScript an object literal is defined as follows:

var myObject = {
    sProp: 'some string value',
    numProp: 2,
    bProp: false

Object literals are used as a means of encapsulating data, enclosing it in a tidy package to minimize the use of global variables which can cause problems when combining code.

How and Why We Use Object Literals

Several scripts from dyn-web use objects literals for setup purposes. Objects literals enable us to write code that supports lots of features yet still provide a relatively straightforward process for implementers of our code. No need to invoke constructors directly or maintain the correct order of arguments passed to functions, etc.

Object literals are also useful for unobtrusive event handling, as a way of holding data that would otherwise have been passed to functions called from HTML event handler attributes.

There is one drawback: if you are unfamiliar with the syntax, it can be very easy to introduce syntax errors which cause code to stop working. [1]

Object Literal Syntax

Object literals are formed using the following syntax rules:

  • A colon separates property name from value.
  • A comma separates each name/value pair from the next.
  • There should be no comma after the last name/value pair. Most browsers won't object if you add it, but Internet Explorer prior to version 9 will generally trigger an error: 'Expected identifier, string or number'.

Values can be of any data type, including array literals, functions, and nested object literals. Here is an object literal from a Rotating Images example demonstrating an array literal property:

var myRotator = {
    path: 'images/', 
    speed:  4500,
    // an array literal
    images: ["smile.gif", "grim.gif", "frown.gif", "bomb.gif"]

The following example from a Tooltip demo demonstrates nested object literal properties:

dw_Tooltip.content_vars = {
    // nested object literal
    link1: {
        img: 'images/dw-btn.gif',
        txt: 'dyn-web button',
        w: 100
    link2: {
        img: 'images/dot-com-btn.gif',
        txt: ' button',
        w: 184

Notice in the examples above that the property names are not enclosed in quotes. It is not necessary to enclose the name in quotes as long as it is a valid identifier and not a reserved keyword in JavaScript.

If any of the syntax rules are broken, such as a missing comma or colon or curly brace, a JavaScript error will be triggered. Both Firefox's and Internet Explorer's error messages are helpful in pointing out the general location of object literal syntax errors. They will not necessarily be completely accurate in pointing out the nature of the error though. If you are not sure where to find the error messages, see our tutorial on JavaScript Errors for more information.

Adding Properties to an Object

You may upon occasion find you need to add properties and values to an object literal that has previously been defined. For example you could add properties to the dw_Tooltip.content_vars object demonstrated above using the following syntax:

dw_Tooltip.content_vars['link3'] = 'content for link 3';
dw_Tooltip.content_vars['link4'] = {
    caption: 'A Heron',
    img: 'images/heron.gif',
    txt: 'A heron image created from a character font.',
    wrapFn: dw_Tooltip.wrapTextByImage,
    w: 210

Be sure to observe the syntax differences when adding properties this way. Each property assignment includes the object name followed by the property name enclosed in quotes inside square brackets. An equals sign rather than a colon separates property and value, and an optional semicolon ends the assignment rather than a comma.

You can use dot syntax to add properties if you are sure your property names will not contain special characters or be reserved keywords in JavaScript:

dw_Tooltip.content_vars.link3 = 'content for link 3';

The above approach might be acceptable for adding a few properties, but it is quite verbose. Use of a function can make the job easier and more concise.

Function for Adding Properties

The augment function below adds the properties of one object literal to another object literal:

// add properties of Obj2 to Obj1
function augment(Obj1, Obj2) {
    var prop;
    for ( prop in Obj2 ) {
        if ( Obj2.hasOwnProperty(prop) && !Obj1[prop] ) {
            Obj1[prop] = Obj2[prop];                

For example, suppose the following is an object literal whose properties you want to add to myObject presented at the top of the page:

var myObject2 = {
    propA: 'Another property',
    propB: 'Me too!'

Call the augment function specifying as the first argument the object to which you want to add the second argument's properties:

augment(myObject, myObject2;)
// to verify

Since one purpose of object literals is to minimize impact on the global namespace, if the augment function is included as a method of an object or class in your library, you can wrap your new properties in an immediate function[2] and call the augment method without any additional impact on the global namespace:

    // props to add to myObject
    var Obj = {
        propA: 'Another property',
        propB: 'Me too!'
    // if augment is method of myLib object 
    myLib.augment(myObject, Obj);
})(); // invoke immediately

Back to top

  1. Licensed users of dyn-web code receive assistance in handling problems they encounter in implementing the code they have purchased. ^
  2. An immediate function is invoked as soon as it is defined. See more information at ^