Accessing Array Elements

Now that you can create an array, let's read its elements one by one.

Every element has its position in the array, called its index. Indexes are counted from zero: the first element has index 0, the second index 1, the third index 2, and so on. You can think of the index as the number of steps from the start of the array: the first element is right at the start, zero steps away.

const resolutions = ["Write a diary", "Take a falconry course", "Learn to juggle"];

Here "Write a diary" has index 0, "Take a falconry course" index 1 and "Learn to juggle" index 2.

To get an element, write the array's name and then the element's index in square brackets:

console.log(resolutions[0]);
console.log(resolutions[2]);

This prints:

Write a diary
Learn to juggle

An element you read like this is an ordinary value, so you can also store it in a variable:

const firstResolution = resolutions[0];
console.log("First:", firstResolution);

This prints:

First: Write a diary

Watch out for the most common mistake with arrays: because counting starts at 0, the last of three elements has index 2, not 3. If you ask for an index where there is no element, JavaScript doesn't report an error. You get undefined, a special value that means “nothing is here”:

console.log(resolutions[3]);

This prints:

undefined

So when you see undefined instead of the element you expected, check the index.

Instructions

Print the first coworker in the array coworkers: console.log(coworkers[0]);

Create a constant favoriteCoworker and store one coworker of your choice in it. Read the name from the array by its index, for example coworkers[2].

Print the constant with a label: console.log("Favorite:", favoriteCoworker);. The console should show, for example, Favorite: Emily.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

3/11

Next