Alfred’s JavaScript Notes: Arrays

JavaScript-logo-150I’m sick of going looking for this information across the web when I need it. So I’m putting it all together in one place. This is for my own use, but you’re welcome to reference it as well, if you find it useful. Just so it’s been said: the canonical online reference (IMO) is the Mozilla Developer Network, aka MDN.

Creating Arrays

Two ways of creating empty arrays:

var arr1 = new Array();

var arr2 = [];

You can also create them with elements (i.e. not so empty):

var arr1 = new Array('elem 1', 'elem 2', 'elem 3');

var arr2 = ['elem 1', 'elem 2', 'elem 3'];

And you can create them with a specified number of undefined elements:

var arr1 = new Array(3);   // [undefined, undefined, undefined]

var arr2 = [3];            // ***not the same: [3]

Adding Elements To An Array

You can add elements to an array:

arr1[0] = 1;   // [1]
arr1[1] = 2;   // [1, 2]
arr1[2] = 3;   // [1, 2, 3]
arr1[5] = 4;   // [1, 2, 3, undefined, undefined, 4]

This method is a little messy because you must remember the index.

JavaScript allows you to add elements without remembering the index.

arr1.push(1);   // [1]
arr1.push(2);   // [1, 2]
arr1.push(3);   // [1, 2, 3]

Look Ma! No undefined elements!

Array.push() allows you to add elements to the end of the array. Array.unshift() is a way to add elements to the beginning of your array:

arr1.unshift(1);     // [1]
arr1.unshift(2);     // [2, 1]
arr1.unshift(3);     // [3, 2, 1]
arr1.unshift(5, 4);  // [5, 4, 3, 2, 1]

Array Length

Easy-peasy: length is a property of the Array object. So you use like so:

var arr1 = [1, 2, 3, 4];
arr1.length;   // 4

More To Come

That’s enough for today. But I’ll be adding more soon.

One thought on “Alfred’s JavaScript Notes: Arrays

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.