Advertisement
Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →
This post is part of a series called JavaScript Succinctly.
Function Prototype Property
Math Function

An array is an ordered list of values typically created with the intention of looping through numerically indexed values, beginning with the index zero. What you need to know is that arrays are numerically ordered sets, as opposed to objects which have property names associated with values in non-numeric order. Essentially, arrays use numbers as a lookup key, while objects have user-defined property names. JavaScript does not have true associative arrays, but objects can be used to achieve the functionality of associative arrays.

In the following sample, I store four strings in myArray that I can access using a numeric index. I compare and contrast myArray to an object literal mimicking an associative array.

Sample: sample133.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = ['blue', 'green', 'orange', 'red'];

	console.log(myArray[0]); // Logs blue using the 0 index to access the string in myArray.

	// Versus

	var myObject = { // aka an associative array/hash, known as an object in JavaScript.
		'blue': 'blue',
		'green': 'green',
		'orange': 'orange',
		'red': 'red'
	};

	console.log(myObject['blue']); // Logs blue.

</script></body></html>

Arrays can hold any type of values, and these values can be updated or deleted at any time.

If you need a hash (aka associative array), an object is the closest solution.

An Array() is just a special type of Object(). That is, Array() instances are basically Object() instances with a couple of extra functions (.length and a built-in numeric index).

Values contained in an array are commonly referred to as elements.


Array() Parameters

You can pass the values of an array instance to the constructor as comma-separated parameters (new Array('foo', 'bar');). The Array() constructor can take up to 4,294,967,295 parameters.

However, if only one parameter is sent to the Array() constructor and that value is an integer ('1', '123', or '1.0'), it will be used to set up the length of the array, and will not be used as a value contained within the array.

Sample: sample134.html

<!DOCTYPE html><html lang="en"><body><script>

	var foo = new Array(1, 2, 3);
	var bar = new Array(100);

	console.log(foo[0], foo[2]); // Logs '1 3'.
	console.log(bar[0], bar.length); // Logs 'undefined 100'.

</script></body></html>

Array() Properties and Methods

The Array() object has the following properties (not including inherited properties and methods):

Properties (Array.prototype):


Array Object Instance Properties and Methods

Array object instances have the following properties and methods (not including inherited properties and methods):

Instance Properties (var myArray = ['foo', 'bar']; myArray.length;):

Instance Methods (var myArray = ['foo']; myArray.pop();):


Creating Arrays

Like most of the objects in JavaScript, an array object can be created using the new operator in conjunction with the Array() constructor, or by using the literal syntax.

In the following sample, I create the myArray1 array with predefined values using the Array() constructor, and then myArray2 using literal notation.

Sample: sample135.html

<!DOCTYPE html><html lang="en"><body><script>

	// Array() constructor.
	var myArray1 = new Array('blue', 'green', 'orange', 'red');

	console.log(myArray1); // Logs ["blue", "green", "orange", "red"]

	// Array literal notation.
	var myArray2 = ['blue', 'green', 'orange', 'red'];

	console.log(myArray2); // logs ["blue", "green", "orange", "red"]

</script></body></html>

It is more common to see an array defined using the literal syntax, but it should be noted that this shortcut is merely concealing the use of the Array() constructor.

In practice, the array literal is typically all you will ever need.

Regardless of how an array is defined, if you do not provide any predefined values to the array, it will still be created but will simply contain no values.


Adding and Updating Values In Arrays

A value can be added to an array at any index, at any time. In the sample that follows, we add a value to the numeric index 50 of an empty array. What about all the indexes before 50? Well, like I said, you can add a value to an array at any index, at any time. But if you add a value to the numeric index 50 of an empty array, JavaScript will fill in all of the necessary indexes before it with undefined values.

Sample: sample136.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = [];
	myArray[50] = 'blue';
	console.log(myArray.length); /* Logs 51 (0 is counted) because JS created values 0 to 50 before "blue".*/

</script></body></html>

Additionally, considering the dynamic nature of JavaScript and the fact that JavaScript is not strongly typed, an array value can be updated at any time and the value contained in the index can be any legal value. In the following sample, I change the value at the numeric index 50 to an object.

Sample: sample137.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = [];
	myArray[50] = 'blue';
	myArray[50] = { 'color': 'blue' }; // Change object type from string to Object() object.
	console.log(myArray[50]); // Logs 'Object {color="blue"}'.

	// Using brackets to access the index in the array, then the property blue.
	console.log(myArray[50]['color']); // Logs 'blue'.

	// Using dot notation.
	console.log(myArray[50].color); // Logs 'blue'.

</script></body></html>

Length vs. Index

An array starts indexing values at zero. This means that the first numeric slot to hold a value in an array looks like myArray[0]. This can be a bit confusingif I create an array with a single value, the index of the value is 0 while the length of the array is 1. Make sure you understand that the length of an array represents the number of values contained within the array, while the numeric index of the array starts at zero.

In the following sample, the string value blue is contained in the myArray array at the numeric index 0, but since the array contains one value, the length of the array is 1.

Sample: sample138.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = ['blue'] // The index 0 contains the string value 'blue'.
	console.log(myArray[0]); // Logs 'blue'.
	console.log(myArray.length); // Logs 1.

</script></body></html>

Defining Arrays With a Predefined length

As I mentioned earlier, by passing a single integer parameter to the Array() constructor, its possible to predefine the arrays length, or the number of values it will contain. In this case, the constructor makes an exception and assumes you want to set the length of the array and not pre-populate the array with values.

In the next sample, we set up the myArray array with a predefined length of 3. Again, we are configuring the length of the array, not passing it a value to be stored at the 0 index.

Sample: sample139.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = new Array(3);
	console.log(myArray.length); // Logs 3 because we are passing one numeric parameter.
	console.log(myArray[0]); // Logs undefined.

</script></body></html>

Providing a predefined length will give each numeric index, up to the length specified, an associated value of undefined.

You might be wondering if it is possible to create a predefined array containing only one numeric value. Yes, it is by using the literal form var myArray = [4].


Setting Array Length Can Add or Remove Values

The length property of an array object can be used to get or set the length of an array. As shown previously, setting the length greater than the actual number of values contained in the array will add undefined values to the array. What you might not expect is that you can actually remove values from an array by setting the length value to a number less than the number of values contained in the array.

Sample: sample140.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = ['blue', 'green', 'orange', 'red'];
	console.log(myArray.length); // Logs 4.
	myArray.length = 99;
	console.log(myArray.length); // Logs 99, remember we set the length, not an index.
	myArray.length = 1; // Removed all but one value, so index [1] is gone!
	console.log(myArray[1]); // Logs undefined.

	console.log(myArray); // Logs '["blue"]'.

</script></body></html>

Arrays Containing Other Arrays (aka Multidimensional Arrays)

Since an array can hold any valid JavaScript value, an array can contain other arrays. When this is done, the array containing encapsulated arrays is considered a multidimensional array. Accessing encapsulated arrays is done by bracket chaining. In the following sample, we create an array literal that contains an array, inside of which we create another array literal, inside of which we create another array literal, containing a string value at the 0 index.

Sample: sample141.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = [[[['4th dimension']]]];
	console.log(myArray[0][0][0][0]); // Logs '4th dimension'.

</script></body></html>

This code example is rather silly, but you get the idea that arrays can contain other arrays and you can access encapsulated arrays indefinitely.


Looping Over an Array, Backwards and Forwards

The simplest and arguably the fastest way to loop over an array is to use the while loop.

In the following code, we loop from the beginning of the index to the end.

Sample: sample142.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = ['blue', 'green', 'orange', 'red'];

	var myArrayLength = myArray.length; // Cache array length to avoid unnecessary lookup.
	var counter = 0; // Set up counter.

	while (counter < myArrayLength) { // Run if counter is less than array length.
		console.log(myArray[counter]); // Logs 'blue', 'green', 'orange', 'red'.
		counter++; // Add 1 to the counter.
	}

</script></body></html>

And now we loop from the end of the index to the beginning.

Sample: sample143.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = ['blue', 'green', 'orange', 'red'];

	var myArrayLength = myArray.length;
	while (myArrayLength--) {                // If length is not zero, loop and subtract 1.
		console.log(myArray[myArrayLength]);  // Logs 'red', 'orange', 'green', 'blue'.
	}

</script></body></html>

Conclusion

Now, if you are wondering why I am not showing for loops here, it is because while loops have fewer moving parts and I believe they are easier to read.

And that completes this article on arrays.

Advertisement