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!'); } };
March 28th, 2008 at 3:12 am
[…] 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 […]
July 7th, 2009 at 7:11 am
Hi!
Thanks for showing this better ways, but why exactly are they (much) better?
What’s the benefit?
kind regards.
July 13th, 2009 at 12:32 pm
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