Arrays

Contact Us or call 1-877-932-8228
Arrays

Arrays

Arrays are zero-indexed lists of values. They are a handy way to store a set of related items of the same type (such as strings), though in reality, an array can include multiple types of items, including other arrays.

A Simple Array

var myArray = [ 'hello', 'world' ];

Accessing Array Items by Index

var myArray = [ 'hello', 'world', 'foo', 'bar' ];
console.log(myArray[3]);	 // logs 'bar'

Testing the Size of an Array

var myArray = [ 'hello', 'world' ];
console.log(myArray.length);	 // logs 2

Changing the Size of an Array

var myArray = [ 'hello', 'world' ];
myArray.length = 0;  // truncates the array to zero elements
console.log(myArray.length);	 // logs 0

Changing the Value of an Array Item

var myArray = [ 'hello', 'world' ];
myArray[1] = 'changed';

Adding Elements to an Array

var myArray = [ 'hello', 'world' ];
myArray[myArray.length] = 'new';
myArray.push('newer');

A lot of online code uses the first approach. Since the indexing is zero-based, the length value coincidentally matches the index of the next available spot, so the 'new' item gets added at that location, and the length goes up by one. The second line uses the object nature of arrays, invoking the array's push method to add an item. This, of course, also causes the length to increase by one.

Working with Arrays

var myArray = [ 'h', 'e', 'l', 'l', 'o' ];
var myString = myArray.join('');	 // 'hello'
var mySplit = myString.split('');	// [ 'h', 'e', 'l', 'l', 'o' ]

Array Methods

As full-fledged JavaScript objects, arrays contain a number of built-in methods.

Some Useful Array Methods
Method Description
push(item) Adds the item at the end of the array, increasing the length by 1.
pop() Removes and returns the last item from the array, decreasing the length by 1.
join(delimiter) Returns a single string containing all the elements, concatenated using the specified delimiter. The default delimiter is the comma character. The values used are the string values of the elements - which, for objects, is the result of the objects' toString() method.
split(delimiter) Splits a string into an array of substrings, and returns the new array. Note that the split() method does not change the original string and if the delimiter is not passed, the array returned is of one item, that being the entire array.
Next