An array is a variable that can contain multiple values. An array can be thought of as a book with the array name being the title of the box and the array index being the page number where you find the information.

In JavaScript (and most programming languages), arrays are numbered starting with 0, rather than 1.

An example of an array in JavaScript is:

const ballGames = ['basketball','football','soccer','tennis'];

The array name is ballGames, and it has four values, which are indexed from 0 to 3.

  • ballGames[0] = ‘basketball’
  • ballGames[1] = ‘football’
  • ballGames[2] = ‘soccer’
  • ballGames[3] = ‘tennis’

Using an array

Compare the two pieces of code:

console.log('basketball');
console.log('football');
console.log('soccer');
console.log('tennis');
const ballGames = ['basketball','football','soccer','tennis'];
for (i = 0; i<ballGames.length; i++) {
  console.log(ballGames[i]);
}

Both of these blocks of code have 4 lines. However, it is easy to see that if you had 100 games to list, the first block of code would then have 100 lines, but the second block of code would not get any longer. Only the array would get bigger.

The second block of code has several features that are frequently used with arrays:

  • for statement – the for statement allows you to count through all the values of the index
  • .length – length is a property of an array which tells you how many values are in the array.
  • i – the array has indexes from 0 to length – 1. Any variable name can be used for this index.

Formatting the code of an array

It is often helpful to format the code that defines an array in a way that makes the structure of the array easy to understand. Remember that, in JavaScript, a line of code ends with a semicolon, and white space is ignored.

Here is an example:

const ballGames = ['basketball',
                   'football',
                   'soccer',
                   'tennis'];

References

JavaScript Arrays (w3schools.com)

Comments

Leave a comment