Jump to content

When to Use the Array Literal Notation in JavaScript

0
  chco's Photo
Posted Oct 19 2010 05:06 AM

Below we have an excerpt from Javascript Patterns. In this excerpt the author explains the use of the array literal notation and how you should use it.
Arrays in Javascript, as most other things in the language, are objects. They can be created with the built-in constructor function Array(), but they also have a literal notation and, just like the object literal, the array literal notation is simpler and preferred.

Here’s how you can create two arrays with the same elements in two different ways—using the Array() constructor and using the literal pattern.

// array of three elements
// warning: antipattern
var a = new Array("itsy", "bitsy", "spider");

// the exact same array
var a = ["itsy", "bitsy", "spider"];

console.log(typeof a); // "object", because arrays are objects
console.log(a.constructor === Array); // true


Array Literal Syntax

There’s not much to the array literal notation: it’s just a comma-delimited list of elements and the whole list is wrapped in square brackets. You can assign any type of value to the array elements, including objects or other arrays.

The array literal syntax is simple, straightforward, and elegant. After all, an array is just a zero-indexed list of values. There’s no need to complicate things (and write more code) by including a constructor and using the new operator.

Array Constructor Curiousness

One more reason to stay away from new Array() is to avoid a possible trap that this constructor has in store for you.

When you pass a single number to the Array() constructor, it doesn’t become the value of the first array element. It sets the length of the array instead. This means that new Array(3) creates an array with length of 3, but no actual elements. If you try to access any of the elements, you get the value undefined because the elements don’t exist. The following code example shows the different behavior when you use the literal and the constructor with a single value.

// an array of one element
var a = [3];
console.log(a.length); // 1
console.log(a[0]); // 3

// an array of three elements
var a = new Array(3);
console.log(a.length); // 3
console.log(typeof a[0]); // "undefined"


Although this behavior might be a little unexpected, it gets worse when you pass a floating point number to new Array() as opposed to an integer. This results in an error because the floating point is not a valid value for the array’s length:

// using array literal
var a = [3.14];
console.log(a[0]); // 3.14

var a = new Array(3.14); // RangeError: invalid array length
console.log(typeof a); // "undefined"


To avoid potential errors when creating dynamic arrays at runtime, it’s much safer to stick with the array literal notation.

Note: There are some clever uses of the Array() constructor though, for example, for repeating strings. The following snippet returns a string with 255 white spaces (why not 256, I’ll leave the curious reader to think about):

var white = new Array(256).join(' ');


Check for Array-ness

Using the typeof operator with array operands returns “object.”

console.log(typeof [1, 2]); // "object"


Although this behavior makes sense (arrays are objects), it’s not too helpful. Often you need to know if a value actually is an array. Sometimes you can see code checking for the presence of length property or some array method such as slice() to determine “array-ness.” But these checks are not robust because there’s no reason why a nonarray object shouldn’t have properties and methods with the same names. Also people sometimes use instanceof Array, but this check works incorrectly when used across frames in some IE versions.

ECMAScript 5 defines a new method Array.isArray(), which returns true if the argument is an array. For example:

Array.isArray([]); // true

// trying to fool the check
// with an array-like object
Array.isArray({
    length: 1,
    "0": 1,
    slice: function () {}
}); // false


If this new method is not available in your environment, you can make the check by calling the Object.prototype.toString() method. If you invoke the call() method of toString in the context of an array, it should return the string “[object Array]”. If the context is an object, it should return the string “[object Object]”. So you can do something like this:

if (typeof Array.isArray === "undefined") {
    Array.isArray = function (arg) {
        return Object.prototype.toString.call(arg) === "[object Array]";
    };
}


Javascript Patterns

Learn more about this topic from Javascript Patterns.

What's the best approach for developing an application with Javascript? This book helps you answer that question with numerous Javascript coding patterns and best practices. If you're an experienced developer looking to solve problems related to objects, functions, inheritance, and other language-specific categories, the abstractions and code templates in this guide are ideal—whether you're using Javascript to write a client-side, server-side, or desktop application. Author Stoyan Stefanov includes several examples for each pattern as well as practical advice for implementing them.

See what you'll learn


Tags:
0 Subscribe


0 Replies