Arrays in JavaScript

This JavaScript tutorial shows some basic concepts about Array in the JavaScript programming language; such as: define, access an array, insert new item, ...


Sampled by © JavaScriptBank.com

If you've been doing programming for some time, you've probably used arrays. Traditionally, arrays are linear allocations of memory where elements are accessed through indexes. In other words, in "traditional" programming languages, when you create an array, you're allocating a chunk of contiguous bytes which is big enough to save the specified number of elements. Then, you can access each element by using an integer which indicates the position of that element.

When you start using a language, you'll probably have to look at the docs which describe its API. In this case, you'll probably find a reference on JavaScript's Array object. Unfortunately, arrays in JavaScript don't really comply with the definition I've presented in the previous paragraphs. The truth is that arrays are just objects which lets you access its properties through an integer which is used as a subscript. This is the main reason why array access in JavaScript is way slower than it should if the language supported "real arrays" and that's why you can use the traditional for(... in ... ) to enumerate all the elements of the array.

The advantage of using the Array object is that you end up inheriting several useful methods (ex.: splice). Here's a small snippet that shows how to use an array in BLOCKED SCRIPT

var arr = new Array();
arr.push(1);
arr.push(2);
alert(arr.length);

We start by creating a new Array through its "constructor". We then add two elements and use its length property to get the total number of slots in the array.

As you can see, this syntax is a little verbose for creating new arrays. In fact, there's another option: we can use literal arrays. You can see this feature as the equivalent of literal objects (when compared with using functions to create a new objects). Here's how you'd rewrite the previous example with literal arrays:

var arr = [1,2];
alert(arr.length);

Much simpler, right?

It's important to keep in mind that the length property is read/write. What this means is that you, for instance set it to a specific value. When you do this, you'll be increasing or decreasing the "size" of the array. When you decrease the "size", you end up  deleting the elements that fall out of the "current size". For instance, notice what happens when you run the next snippet:

var arr = [1,2];
arr.length = 1;
for (var a in arr) {
    alert(arr[ a ]);
}

By running the previous snippet, you'll end up with an array that has only one element (in the previous case, the value 1). Notice that the length property won't really tell you the number of items that are stored on an array. For instance, take a look at the following snippet:

var arr = [];
arr[100] = 10;
alert(arr.length);

When you run the previous snippet, you'll end up getting the value 101. Why? Well, that happens because when you pass the index (arr[100]), you end up influencing the value of the length property. The moral of the story is simple: if you pass an integer to the [] operator that is bigger than the current length's value, you'll  end up updating the value of the length property to that value + 1. Notice that this doesn't mean you're allocating space for the new elements. You're only changing the current value of the length property.

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:

arr.push(12);

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.

Language
Translate this page to English Translate this page to French Translate this page to Vietnamese

Recent articles
Insights for Advanced Zooming and Panning in JavaScript Charts
How to open a car sharing service
Vue developer as a vital part of every software team
Vue.js developers: hire them, use them and get ahead of the competition
3 Reasons Why Java is so Popular
Migrate to Angular: why and how you should do it
The Possible Working Methods of Python Ideology
JavaScript Research Paper: 6 Writing Tips to Craft a Masterpiece
Learning How to Make Use of New Marketing Trends
5 Important Elements of an E-commerce Website


Top view articles
Adding JavaScript to WordPress Effectively with JavaScript Localization feature
Top 10 Beautiful Christmas Countdown Timers
Top 10 Best JavaScript eBooks that Beginners should Learn
65 Free JavaScript Photo Gallery Solutions
16 Free Code Syntax Highlighters by Javascript For Better Programming
Best Free Linux Web Programming Editors
Top 50 Most Addictive and Popular Facebook mini games
More 30 Excellent JavaScript/AJAX based Photo Galleries to Boost your Sites
Top 10 Free Web Chat box Plug-ins and Add-ons
The Ultimate JavaScript Tutorial in Web Design


Free JavaScript Tutorials & Articles
at www.JavaScriptBank.com