Skip to content


JavaScript Object Literal Notation

A few months ago I came across a post by Dustin Diaz titled JSON for the masses. As some comments in the post suggest, his examples are not actually JSON (commonly used as a data interchange format) because the member names are not quoted. But the main point of the article is actually on JavaScript’s “object literal notation”, a method of creating object literals.

It’s quite simple. Douglas Crockford writes:

In the object literal notation, an object description is a set of comma-separated name/value pairs inside curly braces. The names can be identifiers or strings followed by a colon.

Thus, you can create an object like this:

var myObject = {
    name: "Peter Foti",
    'course': 'JavaScript',
    grade: 'A',
    level: 3
};

At first, I found this style somewhat awkward. But the more I use it, the more natural it seems. It’s also quite useful for creating self-invoking objects or namespaces to keep your global objects to a minimum. For example:

var FOTI = function () {
    return {
        name : "Peter Foti",
        init : function() {
            alert('Initializing!');
        }
    };
}(); // Self invoking
window.onload = FOTI.init;

Posted in General, Web Development.

3 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. a question about parameters in the object literal notation. can you only have literals as parameters or you also have parameter values be functions like so:
    name = {

    parameter1 : document.getElementById(‘id’);
    function1 : function() {
    code…
    }
    }

    Please reply

    THANKS THANKS THANKS

  2. Yes, you can have parameter values as functions. They can hold anything a normal variable can hold… strings, numbers, booleans, arrays, or objects (am I forgetting anything?). Here’s a quick example:

    
    var person = {
        name : 'Peter Foti',
        weight : 175,
        eatDonut : function() {
            this.weight += 5;
        }
    };
    alert( person.name + " has a weight of " + person.weight );
    person.eatDonut();
    alert( "After a donut, the new weight is " + person.weight );
    
    
  3. Nikola said

    i just stumbled upon this blog. Great post! The donut example is hilarious.

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.