Accessing Array Elements
In the previous exercise, we learned how to create an array. Now we will look at how to access individual elements in an array.
Each element in an array has an index, which is its position in the array. Array indices start at zero. This means that the first element has an index of 0, the second element has an index of 1, and so on.
Let's look at an example:
const newYearResolutions = ["Write a diary", "Attend a falconry course", "Learn to juggle"];
In this example, "Write a diary"
is at index 0, "Attend a falconry course"
is at index 1, and "Learn to juggle"
is at index 2.
If we want to access the first element in the newYearResolutions
array and print it, we use square brackets with the index of the element we want to access. For example:
console.log(newYearResolutions[0]);
// Prints: Write a diary
Similarly, we can access other elements in the array and print them:
console.log(newYearResolutions[1]); // Prints: Attend a falconry course
console.log(newYearResolutions[2]); // Prints: Learn to juggle
Or we can store the value in a variable:
firstResolution = newYearResolutions[0];
Instructions
Store one coworker from the coworkers
array in a variable named favoriteCoworker
.
Print the value of the variable favoriteCoworker
.
Start programming for free
3/10