5 notes on JavaScript Arrays

In this post, we will go through some of the features of JavaScript's Arrays. I thought this would be a good place to come back time to time and refresh my memory about special cases and notes I've collected on Arrays in Javascript. Without futher ado, 5 notes on JavaScript Arrays.

1. Arrays are Objects in JavaScript

Arrays are Objects in JavaScript. Let me repeat it one more time: "Arrays are Objects". Understanding this helped me simplify my conceptual understanding of the language. Instead of rembembering different special cases and syntax for Arrays and Objects, now, we just need to remember rules to work with Objects alone.

Now, let me elaborate on it more. Array index keys are just property names of an object. Since, a property name can not start with a number, we have to use alternative [''] property access notation just like we would with any other object. So, there is nothing special about Array keys. They are just object property names that are integers.

var array = [1, 2, 'three', 4, 5]; // or 'new Array()'

array.0    // SyntaxError: Unexpected number
array[0]   // 1
array[2]   // 'three'

2. Arrays keys are String

Internaly javascript engine keeps array keys as String values, because naming rules do not allow properties starting with a numeral. When you access array values with an integer, javascript engine casts it into string. So this means that JavaScript Arrays are not breaking any of the naming rules defined by the language. Property names are not starting with an integer and they are stored as strings. Let's see some examples.

var array = [1, 2, 'three', 4, 5];

array[1]                 // 2
array['1']               // 2 - Accessing with a string works just fine
array['3'] == array[3]   // 'true'
array['03'] == array[3]  // 'false' - because array['03'] != array['3']
array['03'] == array[03] // 'false'

In the example above: array['03'] is not equal to array[03], because numerical value 03 furst turned into 3 and only then casted into string. So the end equation would become array['03'] == array[3] and that equals to false.

3. Arrays keys must be positive integers

Just like in any other programming language, JavaScript imposes a rule that array keys can only be positive integers. You can still treat them as if they were objects and set values to any keys. Javascript engine would simply ignore them.

var array = [1, 2, 'three', 4, 5];

array['06'] = 7;
array['str'] = 'some value';
array.prop = 'another value';

console.log( array );  // [1, 2, 'three', 4, 5]

array['6'] = 7;
console.log( array );  // [1, 2, 'three', 4, 5, undefined, 7]

4. Use the literals notation [] instead of new Array()

The new Array() is ambiguous in how it deals with its parameters, so it is better to always use alternative [] notation to define arrays. The literals are more readable and shorter as well.

You can read more about this behaviour here.

// Prefered method
var array = [1, 2, 'three', 4, 5];

// Not so prefered
var array2 = new Array(5);

5. Loop through arrays with for() loop

As we said previously, arrays are objects. So you can loop through them using for in loop. But it is not recommended. Because, for in loops through all the properties that are in the prototype chain and you will have to use .hasOwnProperty() check. This means only 2 things:

  1. bloated and hard to read code;
  2. performance penalty.
var array = [];
a[1000] = 'some value';

for (key in array) {
  if (a.hasOwnProperty(key)) {
    array[key]; // 'some value'
  }
}

// Recommended
for(var index = 0, l = array.length; index < l; index++) {
  array[index]; // 'some value'
}

// OR if you have ECMAScript5 support
array.forEach(function(value) {
    value; 'some value'
});

6. Bonus notes

Since arrays are objects of an Array class. We can check if an object is an array.

function is(type, obj) {
  var clas = Object.prototype.toString.call(obj).slice(8, -1);
  return obj !== undefined && obj !== null && clas === type;
}

is('Array', [1, 2, 3]); // true

If you have jQuery included on your page, use either $.type() or $.isArray().

var array = [1, 2, 3];

$.type(array);     // 'array' - string
$.isArray(array);  //  true   - boolean