Array Surgery - Part 1, The Essentials
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.
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 | // create an array using a constructor met |
Use [ ] instead
1 | var myNumbers = new Array(); // bad |
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 | var myArr = ["I'm", "learning", "how", "to", "create", "arrays"]; |
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 | var myArr = ["Hello", "Hi", "Bonjeur", "Ola", "Ciao'"]; |
You can also add elements to an array:
1 | myArr[20] = "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 | var seasons = ["Summer", "Autumn, "Spring", "Winter"]; |
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 | var names = ["Moe", "Shandy", "Michelle", "Omar"]; |
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 | var names = ["Moe", "Shandy", "Michelle", "Omar", "Mohammad"]; |
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 | var myArr = [1, 2, 3, 4, 5, 6, 7, 8, 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 | var animals = ["Cow", "Rabbit", "Pig", "Horse", "Giraffe"]; |
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 | var animals = ["Cow", "Rabbit", "Pig", "Horse", "Giraffe", "Monkey"]; |
Similarily, the push()
method appends values to an array and relies on the length
property to determine where to start inserting values.
1 | var animals = ["Cow", "Rabbit", "Pig", "Horse", "Giraffe", "Monkey"]; |
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 | var myDogs = ['Alex', 'Marley', 'Ziggy', 'Doggy']; |
A simple example of the unshift()
method:
1 | var myArr = [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.