JavaScript array literal notation rating not rated
SoftXML
                  Programming Books
                Open Web Directory
           SoftXMLLib | SoftEcartJS
xml products   Home page    contact    site map
Contact Us
Latest Blog Articles:   Latest SEO Articles | RSS Feed
DOM manipulation best practices
JavaScript Module Pattern
How to start developing with the Nextjs
Angular application structure
Write Guest Articles
Articles Archive




Loading...

The Art & Science of JavaScript ($29 Value FREE For a Limited Time)
The Art & Science of JavaScript ($29 Value FREE For a Limited Time)









JavaScript array literal notation


Arrays, like so much more in the JavaScript, are objects. Arrays can be created using the built-in Array() constructor, but in the same way they can be created using literals. And like object literals, array literals are easier and more preferable to use.

The following example demonstrates the creation of two arrays with the same set of elements in two different ways - using the Array() constructor and using a literal (you can change the code in the sandbox below and then press execute button).

Array literal syntax

The syntax of array literals is very simple: it is a list of elements separated by commas, enclosed in square brackets. Array elements can be any type of value, including objects and other arrays.

The syntax of array literals is transparent and elegant. After all, an array is just a list of values, the numbering of which starts from zero. There is no need to complicate the procedure of creating arrays (and write more cumbersome code) using the constructor and the new operator.

Oddities of the Array constructor

Another reason you should try to avoid using new Array() is because of the traps this constructor has prepared for you.

When a single number is passed to the Array() constructor, it does not become the first element of the array. Instead, the number is interpreted as the size of the array. That is, calling new Array(3) will create an array with a length equal to 3, but without elements.

If you try to access any of the elements of such an array, you will get the value undefined, because the elements are actually absent. The following example demonstrates differences in the behavior of arrays created using a literal and a constructor with a single value.


// array with one element
var a = [3];
alert(a.length); // 1
alert(a[0]); // 3

// array with three elements
var a = new Array (3);
alert(a.length); // 3
alert(typeof a[0]); // “undefined”

This behavior of the constructor is unexpected, but the situation is even worse if you pass to the new Array() constructor not a whole number, but a floating-point number. Such a constructor call will fail because a floating-point number cannot be used as the length of the array:


// use array literal
var a = [3.14];
alert(a [0]); // 3.14

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

To avoid such errors when creating arrays at runtime, it is better to use array literals.

Checking Arrays

When applied to arrays, the typeof operator returns the string “object”.


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

Although this behavior of the operator is justified in some ways (arrays are objects), but it carries a little information. It is often necessary to know exactly if a certain value is an array.

Sometimes you may find code that checks for the length property or other methods that arrays have, such as slice(). But all these checks are not reliable, because there is nothing that would prevent other objects that are not arrays from having properties and methods with the same names.

Sometimes the instanceof construct is used to verify Array, but it gives erroneous results in some versions of IE.

ECMAScript 5 defines a new method, Array.isArray(), which returns true if its argument is an array. For instance (you can change the code in the sandbox below and then press execute button):

If this new method is not available in your environment, you can check using the Object.prototype.toString() method.

If you call the call() method of the toString function in the context of the array, it should return the string "[object Array]". In the context of an object, this method should return the string "[object Object]". This way you can implement your own validation as shown below:


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

Tag cloud

"[object

"second"

(typeof

(you

//

1  

=== Array Array()

ArrayisArray

a);

array arrays behavior

change

checks

code constructor

context

created

creating

demonstrates

elements

exactly

example

execute

floatingpoint

function literal literals method

methods

number object objects
Rate This Article
(votes 2)

No Comments comments

Post Comment

We love comments on this blog - they are as important as anything we write ourself. They add to the knowledge and community that we have here. If you want to comment then you�re more than welcome � whether you feel you are a beginner or an expert � feel free to have you say.



* = required
Leave a Reply
Name *:
Email *
(will not be published):
Website:
Comment *:
Human Intelligence Identification *:
What is the background color of this web page?
  
Close
Please enter a valid email Please enter a valid name Please enter valid email Please enter valid name Enter valid year
™SoftXML.   Privacy Statement  |  Article Archive  |  Popular Web Development Books
^Top