Fork me on GitHub

Ahad Bokhari

Array Surgery - Part 1, The Essentials

Edit   ·   words

Arrays are used to store multiple values in a single variable. They are list-like objects, yet their elements aren’t fixed; especially when using the length property. They are zero-indexed, meaning the first element of an array is at an index of 0. Therefore the last element will always be the value of the length property minus 1.

Note: The Array.prototype has methods to perform traversal and mutation operations.

Arrays vs. Objects

Saving yourself some trouble down the road, understanding when to use an array or an object is important. As a start remember that we usually want to find a value in an array vs a property of an object. This can be done with indexOf() in an array and hasOwnProperty() in an object. That said, perhaps the most valuable lesson that you should know is that arrays have order and objects don’t.

If you want a more elaborate explanation find out more on MDN

Creating an Array

There are two ways to create an array, via a constructor and using a literal.

1
2
3
4
5
6
7
// create an array using a constructor met
var myArr = new Array(); // notice the new operator
console.log(myArr);

// create an array using the array literal
var myArr = []
console.log(myArr);

Use [ ] instead

1
2
3
4
5
var myNumbers = new Array(); // bad
var myNumbers = []; // good

var myNumbers = new Array(100, 200, 300, 400, 500); // bad
var myNumbers = [100, 200, 300, 400, 500]; //good

While both do exactly the same thing, for readability, execution and speed the array literal method is preferred so just use that.

To access elements of an array is trivial:

1
2
3
4
5
var myArr = ["I'm", "learning", "how", "to", "create", "arrays"];
myArr[1]; //==> "learning"
console.log(myArr); // ["I'm", "learning", "how", "to", "create", "arrays"]

// we'll see later that we can even have variables of different types in an array!

Array Properties, Adding Elements & Looping Through an Array

The real power of an array lies in-built properties and methods. The first property you encounter is the length property:

1
2
var myArr = ["Hello", "Hi", "Bonjeur", "Ola", "Ciao'"];
console.log(myArr.length); //==> 5

You can also add elements to an array:

1
2
myArr[20] = "Yo!"; 
//==> [ 'Hello', 'Hi', 'Bonjeur', 'Ola', 'Ciao\'', , , , , , , , , , , , , , , , 'Yo!' ]

Beware of using the length property as it could be misleading:

  • Use right index to insert positive integers, use positive integers as an index
  • Don’t randomly insert by index unless you are inserting the element in the right place. This will save you alot of memory as your programs grow
  • When adding elements to an array be wary as it creates a hole that is undefined as you see above

Things start getting interesting when you loop through an array - there are quite a few concepts that you can apply but the best use would be a sequential for loop. Try to avoid using for-in as that is used to enumerate over object properties.

An extremely useful article on this topic can be found on Stack Overflow: Looping through an Array

A simple for loop can be demonstrated below:

1
2
3
4
5
6
var seasons = ["Summer", "Autumn, "Spring", "Winter"];
var seasonsLength = seasons.length;
for (for var i = 0; i < seasonsLength; i++) {
console.log(seasonsLength[i]);
// do something cool
}

In this example note that (a) the order is guaranteed and (b) inherited properties are not also enumerated.

Extra Stuff

Recognizing an array using typeOf():

1
2
var names = ["Moe", "Shandy", "Michelle", "Omar"];
console.log(typeof names); // returns [object] because a JavaScript array is an object

Using indexOf() to search an array for a specified item and return it’s position. The indexOf() method will start at the specified position, or at the beginning if no start position is specified, and end the search at the end of the array:

1
2
3
4
5
6
7
8
9
10
var names = ["Moe", "Shandy", "Michelle", "Omar", "Mohammad"];
console.log(names.indexOf("Shandy")); // ==> outputs 1

//another example below
var arr = [2, 5, 9];
arr.indexOf(2); // 0
arr.indexOf(7); // -1
arr.indexOf(9, 2); // 2
arr.indexOf(2, -1); // -1
arr.indexOf(2, -3); // 0

Even though this is a method I wanted to introduce it here first, before we move onto the next section.

Another little obscurity in arrays, delete doesn’t actually delete. Remember being wary of the length property?

1
2
3
4
var myArr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
delete myArr[3];
console.log(myArr); // ==> [ 1, 2, 3, , 5, 6, 7, 8, 9 ]
console.log(myArr.length) //==> outputs 9

Methods of An Array

Fantastic, you’ve gotten way beyond the fold. Continuing dissecting our arrays we move onto interesting default methods of the array. This is where the strength of JavaScript arrays lies; remember that arrays are the top 3 most used data structures in the language which makes it a must to master them.

Let’s start out with the basic methods pop(), push(), slice(), splice(), shift() and unshift() and then in part two we build our way up with callback functions with the cast of map(), filter() and forEach().

First, let’s think about converting arrays to strings, which can be common when working with the DOM. For JavaScript arrays, valueOf() and toString() are equal as in they both return an array as a string.

1
2
3
4
5
6
7
8
var animals = ["Cow", "Rabbit", "Pig", "Horse", "Giraffe"];
document.getElementById("my-array").innerHTML = animals.valueOf();

// we can use the same <code>toString()</code> to achieve the same results.
document.getElementById("my-array").innerHTML = animals.toString();
//==> outputs Cow, Rabbit, Pig, Horse, Giraffe

// The join() method also joins all array elements into a string

When you’re working with an array, you need to be able to remove and add elements. You can do that with simple methods like pop() and push().

The pop method simply removes the last element in the array and returns that value to the caller:

1
2
3
var animals = ["Cow", "Rabbit", "Pig", "Horse", "Giraffe", "Monkey"];
var animalsPopped = animals.pop();
console.log(animalsPopped); // ["Cow", "Rabbit", "Pig", "Horse", "Giraffe"];

Similarily, the push() method appends values to an array and relies on the length property to determine where to start inserting values.

1
2
3
4
5
var animals = ["Cow", "Rabbit", "Pig", "Horse", "Giraffe", "Monkey"];
var total = animals.push("Rhinoceros", "Cat");

console.log(animals); // ["Cow", "Rabbit", "Pig", "Horse", "Giraffe", "Monkey"]
console.log(total); // 8
Note: the methods described here are all inherited from Array.Prototype and all of them listed below can be used with call() and apply() on arrays that are similar to objects.

The shift() and unshift() methods also both work on first element of the array - using some variables and concatenation, let’s explore the difference between the two:

1
2
3
4
5
6
7
8
9
10
11
12
var myDogs = ['Alex', 'Marley', 'Ziggy', 'Doggy'];
console.log('myDogs before: ' + myDogs);

var myDogsShifted = myDogs.shift();

console.log('myDogs after: ' + myDogs);
console.log('Removed this element: ' + myDogsShifted);

//==>
myDogs before: Alex,Marley,Ziggy,Doggy
myDogs after: Marley,Ziggy,Doggy
Removed this element: Alex

A simple example of the unshift() method:

1
2
3
4
5
6
7
8
9
10
var myArr = [10, 20, 30];

myArr.unshift(0);
// [0, 10, 20, 30]

myArr.unshift(-10, -20);
// [ -10, -20, 0, 10, 20, 30 ]

myArr.unshift([-5]);
// [ [ -5 ], -10, -20, 0, 10, 20, 30 ]

We’ve defined an array and listed quite a few array methods to get you started off with. As noted there are more basic methods that we can use: map, filter and forEach and we can discuss those in another post.