Using literals

Array literals

In JavaScript you can define an array like this:

var a = new Array();

A better pattern to do so is by using the array literal, basically a comma-delimited list of values, wrapped in square brackets:

var a = []; // array with no elements
var a = [1, 2, 3]; // array with three elements
var a = [[1, 2, 3], ['a', 'b', 'c']]; // array of two arrays

Object literals

Similarly, an empty object can be defined as:

var o = new Object();

A much better pattern is to use the object literal:

var o = {}; // empty object
var o = {p: 'one'}; // object with a "p" property
var o = { 
  prop: 1,  // a property
  meth: function() { // a method
    alert('Boo!');
  }
};

3 Responses to “Using literals”

  1. phpied.com » Blog Archive » JSPatterns.com up again Says:

    […] for anything interesting in the ever so exciting world of JavaScript. So far nothing special there (example), but keep an eye on it, as I plan to fill up the TOC (recovered from the old wiki) with top […]

  2. greasefury Says:

    Hi!
    Thanks for showing this better ways, but why exactly are they (much) better?
    What’s the benefit?
    kind regards.

  3. Hemant Says:

    Hi Stoyan,
    I just started with your book Object Oriented JavaScript. Landed on this website through a reference in book. Stoyan, even Douglas mentions about using array literal instead of new Array(); declaration. Could you please shed some more light on it? As in why using literal is better than using new Array();
    Thanks,
    Hemant