Arrays in JavaScript – part II

In the previous post we’ve started looking at arrays in JavaScript. At the time, we’ve seen that you could initialize a new array by using the constructor or by using the literal syntax. As Daniel pointed out in the comments of the previous entry, there are several ways to initialize an array through its constructor.

In fact, you can call the constructor and pass zero or more parameters. When you don’t pass any, then you’ll end up with a new empty array (this is the example we’ve met in the previous post). You can also pass a single parameter to the array. When you do that, two things can happen:

  • passing a number creates a new array and sets its length property to that value (notice that the array is still empty; the difference is that it the length property isn’t zero);
  • passing a non-number value is the same as creating a new empty array and pushing that item into that new array.

Here’s some code that illustrates both usages:

var arr = new Array(10);//initiate array and set length = 10
var arr2 = new Array(1, 2, 3);
alert(arr.length); //prints 10
alert(arr2.length); //prints 3

Notice that setting the length might introduce some “ambiguities”. For instance, what happens when you run the following code:


Since when we initialized arr we set the length to 10, then push will put the current item (in this case, 12) on position 11 (10, if you’re counting from 0). this might not be intuitive,but it’s how it works.

Notice that if you pass a single non numeric parameter to the array,you’re, in fact, creating a new array which contains only that element:

var arr3 = new Array(''10'');
alert(arr3.length); //prints 1
alert(arr3[0]);//prints string 10

And I guess this wraps up array initialization and construction. Stay tuned for more on JavaScript.


~ by Luis Abreu on September 10, 2009.

One Response to “Arrays in JavaScript – part II”

  1. a little article but it”s still very good for beginners

    Beside, can I share this snippet on my JavaScript library?

    Awaiting your response. Thank

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: