JavaScript Arrays (lists)



I told you earlier that querySelectorAll works the same as querySelector -- except it will return ALL elements that match the selector (instead of just the first).

So, how do we access each element in a list of elements? Well, knowing how Arrays work in JavaScript will help us, so let's learn that now.

An Array is basically a list

// create a new array called myArray and add 3 names to the list
var myArray = ['Alice', 'Bob', 'Charlie'];

// shows an alert with the name 'Alice'
alert( myArray[0] );

// shows 'Bob'
alert( myArray[1] );

// shows 'Charlie'
alert( myArray[2] );

// Change the first item (at index 0) to 'Sandy';
myArray[0] = 'Sandy';

// shows 'Sandy' now (instead of 'Alice')
alert( myArray[0] );

As you can see from above, you access items in the array using their index (which starts at 0), so the first item would be myArray[0], the second myArray[1], and so on.

Adding new items to the Array

// Create an empty array
var myArray = [];

// Manually add names to the empty array
myArray[0] = 'Alice';
myArray[1] = 'Bob';
myArray[2] = 'Charlie';

// Save the array's length (3) to a variable
var length = myArray.length;

// Add a new item to the end of the array

// length is now 4
length = myArray.length;

// Calculate the index for the last item in the array
var lastIndex = length - 1;

// Shows 'Dave'
alert( myArray[lastIndex] );

The code above shows that you can also add new items to the Array after it has been created. You can either use the push function or manually specify the new index. If the array isn't big enough, it will automatically grow itself and create the new slot.

Note: The index for the last item in the array is always 1 less than the array's length.

Leave a Comment