🗃️ Arrays

Lesson

🗃️ Arrays

Arrays are special variables, which can hold more than one value at a time. They can be long or short, and we can have many different arrays in one program.

They store data in a particular order which can be accessed using the index number.

let arrayIndexExample = ['first', 'second', 'third', 'fourth'];
//index =                   0         1        2         3

The first item in an array is always index number 0.

Why are arrays useful?

Arrays come in handy when we have a list of related data. We can loop through an array, and select certain values using the index number.

Instead of storing a list of items as single variables like this:

let fruit1 = 'apple';
let fruit2 = 'banana';
let fruit3 = 'orange';
let fruit4 = 'strawberry';
let fruit5 = 'mango';

We can create an array which stores them all as a list:

let fruitArray = ['apple', 'banana', 'orange', 'strawberry', 'mango'];

This lets us store all of the items under a single name.

We can store different types of data in arrays (eg numbers), but we’re going to focus on strings (words) for now.

To access a certain item in an array, we put the index number inside square brackets like this:

alert(fruitArray[0]);

//apple

How do I make one?

To set up an array, we need to declare it like a variable.

We need to use [square brackets] to show what is inside the array.

// name the array, then declare the items in the array
let candyArray = ['chocolate', 'lollipop', 'sherbert', 'jellybean'];

Remember to use ‘quotation marks’ around each string.

We can add more items to an array by specifying an index number which hasn’t been used yet:

candyArray[4] = 'fruit burst';

alert(candyArray);
//'chocolate', 'lollipop', 'sherbert', 'jellybean', 'fruit burst'

But if we specify an index number that’s already used up we replace that item:

candyArray[2] = 'licorice';

alert(candyArray);
//'chocolate', 'lollipop', 'licorice', 'jellybean', 'fruit burst'

Now sherbert has been replaced by licorice in the array.

Try It Out

Use this link to create arrays with lists of some of your favourite foods:

@

Not recently active