The use of literals vs constructors (new Array vs [] and new Object vs {})

In JavaScript there are two main ways to declare a new object or a new array. One uses literal syntax whilst the other favours the more verbose method of calling the constructor.

var obj = {};
var ar = [];

… or…

var obj = new Object;
var ar = new Array;

Over the years using literal syntax has become the idiomatic way due to the following reasons (and it is because of these reasons that you should also be using them):

  1. The names Object and Array can be overridden, whilst the literal equivalents cannot:

    Array = Object = function () {
        alert('Foo');
    };
    
    var ar = new Array; // alerts "Foo"
    var obj = new Object; // alerts "Foo"
    

    Whilst you may think “I’m never going to override Object or Array so why should I care”, remember there’s nothing to stop 3rd party libraries you include doing this; quite possibly accidentally, but it’ll still break your program.

  2. The object literal allows you to define attributes inline. You cannot do this with the constructor counterpart.

    var obj = {
        prop: 1,
        add: function (val) {
            return this.prop + val;
        }
    };
    
  3. The array constructor has a horrible interface which changes depending on the situation.

    // What do you think ar and ar2 equal?
    var ar = new Array(1);
    var ar2 = new Array(1,2,3,4);
    
    // Probably this?
    alert(ar.join(",") === "1");
    alert(ar2.join(",") === "1,2,3,4");
    

    …. In fact passing one parameter to new Array creates an array whose length is the value passed to the first parameter. The value of each of these elements are undefined. On the other hand passing more than one parameter creates an array whose elements are equal to each of these parameters.

4 thoughts on “The use of literals vs constructors (new Array vs [] and new Object vs {})

  1. Hi Matt. I’m at the point where I just sorta get what you’re saying. I’m 65 and a newbie fascinated with javascript, but I’m in the midst of laughably many hours lost trying to find knowledge that’s apparently far too obvious for teachers to think of teaching: How do I write a TWO-dimensional array in the now-preferred literal way using [ ] as opposed to new Array( ) as per my old books such as Javascript & Ajax for Dummies? I’m attempting to define the 10,000 indices on a rectilinear grid for a random checkerboard gizmo I’m trying to make for fun. W3Schools simply says to avoid using new Array( ), but fails completely, for old brain at least, to elucidate the syntax to designate 100 arrays each consisting of integers 0-99 within an array. My console can’t digest any of my attempts. I’d be most grateful if you have a few seconds to show me how it’s written. However, uh, yeah, sometimes you hotshots (stackoverflow comes to mind) like to show off such shorthand that the notation becomes an even bigger head-scratcher.
    Again, thanks if you can..
    Mike Storer in Arizona City, AZ. Absolute middle of nowhere desert twixt Phoenix and Tucson. Overfly me at coords: -111.6569805555556,32.744175,0

  2. Hi Mike. We’ve all been a newbie once… young or old :). I’d do something like this;

    var a = [];
    
    for (var i=0;i<100;i++) {
        var b = [];
    
        for (var j=0;j<100;j++) {
            b.push(j);
        }
    
        a.push(b);
    }

    … and that should give you a multidimensional array, numbers from 0-99. e.g. a[0][0] will give you 0. a[0][99] will give you 99. a[99][0] will give you 0 and a[99][99] will give you 99! I hope that was what you were after!

  3. Matt, thanks for taking the time to respond with the “egg layer” that outputs the nested array I sought in my prior comment.
    But, tell me: Besides avoiding the questionably more tedious and admittedly less elegant procedure of pasting “[0…99],” 100 times within a pair of brackets, namely a = [ ], to write the initial script, is it true or false that calling upon javascript to loop through 10k integers to have it stuff an empty array a = [ ] each time the script is run is more efficient, faster or -somehow yields an essentially different end result- than what looks to be working for me? I.e, just hard-wiring a = [ ] from scratch like this:

    var a = [
    [0...99], [0...99], ...and pasted in 98 more times, minus a final comma...
    ];

    ??
    Thanks again for the gift of knowledge,
    Mike Storer in AZ

  4. Pondering now what I just asked above…
    Perhaps both methods require exactly the same number of iterations since in either case each integer must somehow be dealt with sequentially and assigned a unique memory registry??
    I guess this betrays my ignorance about how javascript actually works in conjunction with memory, namely whether a running function stores its product in some temporary location and only after afterwards the process of allotting that output into a different area of memory ensues or whether it all occurs synchronously… I hope this makes sense… eeww..

Leave a Reply

Your email address will not be published. Required fields are marked *