JavaScript Object Literal

An object literal is a comma-separated list of name-value pairs wrapped in curly braces. 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.

The following demonstrates an example object literal:

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

Object literal property values can be of any data type, including array literals, functions, and nested object literals.

Here is another object literal example with these property types:

var Swapper = {
    // an array literal
    images: ["smile.gif", "grim.gif", "frown.gif", "bomb.gif"],
    pos: { // nested object literal
        x: 40,
        y: 300
    onSwap: function() { // function
        // code here

Object Literal Syntax

Object literals are defined using the following syntax rules:

  • A colon separates property name[1] from value.
  • A comma separates each name-value pair from the next.
  • There should be no comma after the last name-value pair.[2]

If any of the syntax rules are broken, such as a missing comma or colon or curly brace, a JavaScript error will be triggered. Browser error messages are helpful in pointing out the general location of object literal syntax errors, but they will not necessarily be completely accurate in pointing out the nature of the error.[3]

Why and How We Use Object Literals

Several JavaScripts from dyn-web use objects literals for setup purposes.[4] 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. 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.

Read on to find out how to add, modify and access properties of an object literal.

Back to top

  1. A property name needs to be enclosed in quotes if it contains spaces, other special characters, or a keyword reserved in JavaScript. ^
  2. Most browsers won't object if you add a trailing comma, but Internet Explorer prior to version 9 will generally trigger an error: 'Expected identifier, string or number'. ^
  3. If you are not sure where to find the error messages, see our tutorial on JavaScript Errors for more information. ^
  4. Rotate Images and JavaScript Tooltip are two examples demonstrating extensive use of object literals. ^