JavaScript Arrays

In computer science one of the most helpful and widely used ways of storing information is in lists. Different types of lists have different names. They can be "lists", "vectors", or as in the case of JavaScript "arrays". A list or array in itself can be a singular thing with a name to reference but its main function will always be to hold references to other, existing, things. What it can hold changes from language to language but within the realm of JavaScript this can be almost anything.

There are several reasons to use Arrays within JavaScript - especially when developing for the web. If you've ever been given a list, or table of information on a web page, on some pages you might have the option to reorder the values of the list to be in a particular order. Perhaps alphabetically, chronologically, or by rating, such as with a movie review site or music store. In this case you'll need to run a sorting algorithm to change the positions of values within their row or column. This much easier if those values are within a single list.

Another example would be if you want to iterate over multiple, similar objects. We've already talked about how functions are helpful in that they allow for reusable code. Arrays collect data into lists for a similar reason. Instead of a function having to be called multiple times to work with many different variables we program the function to apply to every piece of data within the array (this is covered in the next section concerning "loops").

Here are some qualities of JavaScript arrays to be aware of if you are coming from another programming language.

  • JavaScript arrays are named just like variables.
  • JavaScript arrays have no hard limit on their size (they are limited by available memory) and this size can change over the course of the program without the need for memory management.
  • JavaScript arrays can store functions as variables.

Creating Arrays

Let's look at how to create and modify a list. First the creation.


<script>

var fruits = ["Apple", "Banana", "Orange"];

</script>

And that's it! We now have a new array that holds three entries.

Making a new array within JavaScript is as simple as declaring a variable with a name and using square brackets to define the set that is your chosen information.

A particular data type or length is not required. All of the entries can be numbers (which will of course not have quotation marks), they can be strings, and the set can be any length.

Adding new entries

You can even create an empty array and add to it later. This is done using a method called "push". This is an inherent method of a JavaScript list and must be written with dot notation after the variable as if the variable were part of a function name itself. This is better explained through example.

Note: we have written what will be returned in the console after the "console.log()" command as comments within these examples.


<script>

var various = [];

various.push("Corgi");
various.push( 6 );
various.push("Dane");
various.push("three");

console.log( various ); 	// Returns ["Corgi", 6, "Dane", "three"]

</script>

Note the use of the keyword "push". This is the name of the function that we call to add new entires to the array. In JavaScript they will be added to the end of the array by default (if there are existing entries to begin with).

If we are adding a new entry that is a standard data type then we write the value as if we were declaring a new variable. Numbers are simply written as numbers, strings are written in quotations, and so on. Because of this the word "three" above will be seen as a word and not as a number - just as it would if you were declaring a variable.

Remember that "push" must be written just as you see it above. It must have a period "." before it, there can not be a space between it and the array name ("array .push"), and it can not be written with a capital "P".

Extracting information

A list wouldn't be very helpful if it could not keep the information separate in some way. Array entries are thankfully easy to identify and extract. This is because they are labled automatically by the order that the come in the list. We can call any entry in the list, regardless of what the recorded data type is, by using a numerical value to denote the list position of that entry. But there is one important concept to remember.

When counting array entries, alway start at zero.

It doesn't matter what language you're using, it is a near universal fact in computer science that the first position of every list is in fact "0" and not "1". This is because of the way that computers naturally count. A "0" value is always a possibility so it would be a waste not to use it during iterations.

The actual way to write a request for an array entry is simple. Write the name of the entry, followed by square brackets, and place the number of the desired entry to retrieve within the brackets.



array_name[7]

The above line will be another way of writing the value that is actually held in the eighth position of the array called "array_name". Of course this alone won't do anything.

Let's look at actual code where in an array is made and a position of that array is written to the console.


<script>

var colors = ["Red", "White", "Blue"];

console.log( colors[0] );		// Returns "Red".
console.log( colors[1] );		// Returns "White".
console.log( colors[2] );		// Returns "Blue".

</script>

There are times when you may wish to either ascribe a new property to a list that isn't a pre-existing variable or perhaps duplicate a list without having to comb through each value to duplicate as well. In such cases it will probably be better to use a JavaScript "object" which will be discussed in the next section.

Inherent Properties and Methods

There are a few functions which are standard across all browsers. All of these methods will be called via the same approach of the array name, a period (as they are accessed via dot notation) and the property name / function call.

Length

The "length" method will return a single integer that represents how many entries there are in the array. So an array of three entries will simply return "3".

It is simple enough to use, simply add ".length" to the end of the array name to have the number returned whever it is used. Remember not to forget the "." as this is required.



When using this method you have to keep in mind how the actual "index" positions of lists start with "0". It can cause confusion because an array of length "10" does NOT have an index position of "10". The last index position available in such an array would be "9".

We can see the effect of this below (along with a trick that will allow you to get the actual last index value if needed).



While it is not technically a method of the JavaScript array object you will often see "length" used in conjunction with a random number to get a random position on a list.

Random numbers can be generated in JavaScript just by writing out "Math.random()". This will return a decimal point number between 0 and 1 (including the possibility of 0 and 1).

When used in conjunction with another math function "floor", which rounds every value down to the nearest whole number, we can get a random index number that is within the length limit of our array.



Essentially the above is saying "Multiply a random fraction times the total size of the array and round the result down to the nearest whole number". This is needed because getting an element from an array has to be done using a whole number that does not have a decimal point fraction.

Sort

".sort" will allow you to quickly sort a single array into ascending values. It works for both numbers and strings.



Push

See above.

splice

TBA

The "splice" method allows you to remove elements from an array (and possibly replace them with new ones if desired).