A Programmer’s Tour Of Javascript


In C-like languages, arrays are a specific kind of data structure that is handled through language semantics. They are uniformly typed, their capacity is fixed at compile time, and they do not have any properties or methods.

But in JavaScript, arrays are objects. Their capacity may grow and shrink at runtime, and they have their own properties and methods (including those that they inherit from the Object prototype). Their elements are like JavaScript variables in that they are not themselves typed. So, JavaScript arrays can hold any kind of data – a primitive type, an object, or even another array.

JavaScript’s array syntax is fairly straightforward to anyone who knows any C-style syntax. The array is delimited by a pair of square brackets, with a comma-separated list of element literals. (This is also what is displayed if you output an array in the console.) To access an individual element, you use the array access operator – a pair of square brackets after the array’s name, with the index of the element in between. Arrays are zero-indexed, and the index should be a positive integer.

Here’s some code that demonstrates all of that:

> var arr = [3.1415, "Hello, world!", /[^a-z0-9]/i, false];
> arr[0];
> arr[1];
  "Hello, world!"
> arr[1].search(arr[2]);
> arr[3] = true;
> arr;
  [3.1415, "Hello, world!", /[^a-z0-9]/i, true]

You can get the length of the array with the array object’s length property. Array lengths are dynamic. This means that there can be no such thing as an “out of bounds” error. If you try to access an element that is out of bounds, the result will be undefined. If you assign a value to an element that is outside the array bounds, the array will immediately be resized to a capacity that can hold that element. If the resizing operation results in empty elements, those elements will be undefined. (This is the same value as an uninitialized variable, so it makes sense.)

Elements can also be deleted using the delete keyword, followed by the name of the array element. This deletes the data but not the index itself; it sets it to the undefined value. So, if you delete an element in the middle of the array, there will be an undefined “gap” at that index, but the oher elements remain exactly as they were. The delete keyword will only work with array elements (and object properties); you can’t delete a variable.

In addition to the length property, JavaScript array objects also have a huge number of useful methods. I’ll group them by purpose.

Searching and sorting:

searches the array for elem, starting at the beginning.
searches the array for elem, starting at the end.
reverses the order of the elements.
sorts the elements of an array. By default, it converts each element into a string, and sorts them in their Unicode character order.

The cmp paramter is an optional comparison function. (You can pass a function as a parameter because they are first-class objects, which I will cover later.) The function should take two parameters, say a and b, and return a numeric value according to their order. If a > b, it should return a positive number; if a < b, it should return a negative number; and if a == b, it should return zero. If you’re comparing number types, you can just return a - b.

Splitting and joining:

returns the original array appended with arr.
slice(start, end)
returns all of the elements between start (included) and end (excluded). If end is omitted, the array’s length is used.
splice(index, num, elems...)
removes num elements from an array, at position index, inserts elems at that index. You can pass any number of elements to insert (including none).

Stack and queue operations:

removes the last element of an array, and returns that element.
adds elem to the end of the array, and returns the new length.
removes the first element of an array, and returns it
adds elems to the beginning of the array, and returns the new length.

String conversion:

joins all the elements into a single string, with delim between the elements. If delim is not provided, a comma character is used.

toString()joins all the elements into a single string, with a comma between the elements.

JavaScript does not have a language construct for creating a multidimensional array (a matrix). This is not surprising; in JavaScript, a “multidimensional array” would be an array whose elements are themselves array objects, and array lengths are always dynamic. This is sometimes called a “jagged array” in other languages. If you want to create a multidimensional array, you have to create it yourself. Here’s the code to do that:

var matrix, row, i, j;
// Create 10x20 matrix
for (i = 0; i < 10; i++) {
    row = [];
    for (j = 0; j < 20; j++) {
        row[j] = null; // ...or a default value...
    matrix[i] = row;

There is one thing I’d like to mention before I finish with arrays. JavaScript has an extended version of the for loop that handles enumerable objects, called the for/in loop. (It is JavaScript’s version of the foreach loop.) It allows you to iterate over all of an object’s enumerable properties without maintaining a numeric index, as you would in a normal for loop.

However, the for/in loop should not be used with arrays. There are a couple of reasons why it’s a bad idea:

  • The loop will only iterate over the elements in an array that are not undefined.
  • There is no guarantee that the elements will be iterated in numeric order.

Instead, you should just use a standard for loop, which has pretty much the same syntax as other C-style languages:

// Log all values in the "arr" array
for (var i = 0; i < arr.length; i++) {
    console.log(i + ": " + arr[i]);

This is a common mistake among programmers new to JavaScript, because the “foreach loops” of other languages do not have these issues, and in fact are used primarily with arrays. Not so with JavaScript; its for/in loop is designed to be used with the properties of objects.

It is also an understandable mistake, because in JavaScript, arrays and objects are very closely related. In fact, the only practical difference is that array elements are indexed by integers, and object elements are indexed by their member names.


About Karl

I live in the Boston area, and am currently studying for a BS in Computer Science at UMass Boston. I graduated with honors with an AS in Computer Science (Transfer Option) from BHCC, acquiring a certificate in OOP along the way. I also perform experimental electronic music as Karlheinz.
This entry was posted in JavaScript, Programming and tagged . Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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