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!');
  }
};

Tags:

3 Responses to “Using literals”

  1. JSPatterns.com » Blog Archive » Constructors Says:

    […] simple way to create objects in JavaScript is using object literal notation. An other way, a bit more involved is to use a constructor […]

  2. JSPatterns.com » Blog Archive » A case against inheritance Says:

    […] easy to follow this advice in JavaScript. Remember - no classes in JavaScript. And how about the object literal, how simple it is? If you can add functionality to your objects from elsewhere – why do you need […]

  3. Karl Oakes Says:

    Why is it better to use literals ? I can see it is more natural to use literals in an object based language, but don’t understand why it is preferred, is the new operator more expensive in terms of instantiation? Surely they are doing the same thing ?

Leave a Reply