How to create an array

JavaScript polyfill, by , Sunday, March 9th, 2014

There are more than one way of creating an array in JavaScript, but the preferred way, and they way considered best practice by most developers, is using literals;

  1. // Declaring an empty array
  2. var arr1 = [];
  3. // Assign values to arr1
  4. arr1[0] = 'more';
  5. arr1[1] = 'is';
  6. arr1[2] = 'possible';
  8. // Doing declaration and assignment in one line
  9. var arr2 = ['this', 'is', 'also', 'possible'];

(You can also use the Array constructor, but it is highly discouraged, and considered bad practice by most developers)

In JavaScript arrays are essentially objects with some special properties, so like objects, you can store anything in an array, even functions and other objects and arrays. You can even store things that have different types in the same array. This means, that you can store numbers, strings, object, functions, etc. in one and the same array, just like this;

  1. var baker = [function () {
  2. return 'mix flour, salt, water. Knit together and bake until golden';
  3. },
  4. {food: 'bread', eat: 'yummy!'},
  5. 42];

This is completely valid to do in JavaScript, even though it contains elements of three different types!

When to use an array and when to use an object?
It is quite simple, if you have a list of elements that either need numeric keys, should appear in a specific order, you should use an array. If on the other hand, you have elements, where the order is not important, but where the keys should be something else than numbers, you should always use an object.