JavaScript Literals

The following offers a brief introduction to JavaScript's literal syntax for defining objects and arrays. This has been included for programmers who might be fairly new to JavaScript programming and have not previously seen this syntax.

Object Literals

A literal syntax exists in JavaScript for object definition. The following code...

var foo = new Object();

foo.alpha = 90;

foo.bravo = function() {
   return 7;

...can be represented as...

var foo = {

    alpha: 90,

    bravo: function() {
       return 7;

The whitespace is of course optional. The following is equivalent, albeit ugly:

var foo={alpha:90,bravo:function(){return 7;}};

Additionally, an empty object may be defined simply as "{}":

var foo = {};

Array Literals

Arrays may also be represented using a literal syntax. The following two snippets of code are effectively identical.

var emptyArray = new Array();

var anArray = new Array("a", "Q", "z");
var emptyArray = [];

var anArray = ["a", "Q", "z"];