JavaScript has a number of different literal syntaxes beyond the standard Number
, String
, Boolean
that are common to other languages:
foo = {};
is the same as:
foo = new Object();
While
foo = [];
is the same as:
foo = new Array();
and
foo = /foo/;
is the same as:
foo = new RegExp('foo');
These literal syntaxes have their own quirks and nuances. For objects, key-value pairs are comma separated with the keys and values separated by colon characters:
foo = {
bar: 'baz',
fizz: 'buzz'
};
is equivalent to:
foo = new Object();
foo.bar = 'baz';
foo.fizz = 'buzz';
For arrays, the array members are simply comma separated:
foo = ['bar', 'baz'];
is equivalent to:
foo = new Array();
foo.push('bar', 'baz');
Note that for arrays the constructor function has a flaw. new Array(1, 2, 3)
is equivalent to [1, 2, 3]
, but new Array(3)
is not equivalent to [3]
, it is instead equivalent to [undefined, undefined, undefined]
(an array of size 3 with no members).
This convenient initialization structure, and the ability to nest objects and arrays within each other is what lead to the formalization of the JSON data interchange format