Accessing Array Elements
Part of the Fundamentals section of Coddy's JavaScript journey — lesson 58 of 77.
In JavaScript, we use arrays to store multiple values in a single variable. Each value in an array is called an element, and each element has an index. The indices start from 0 to the length of the array minus one.
For example, take a look at the next array:
let myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g']- Element
ais at index 0 - Element
bis at index 1 - ...
- Element
gis at index 6
To access an element of an array, we can use its index within square brackets. For example, to access the first element of an array named myArray, we would use myArray[0].
Here's an example:
let myArray = [10, 20, 30, 40, 50]
let element = myArray[2]The variable element will hold the value 30 because it accesses the third element (which has an index of 2).
Challenge
EasyCreate a function named values that receives an array as an argument and prints all of the items in the array one after the other.
To iterate over an array use the .length property inside the for statement:
let myArray = [10, 20, 30, 40, 50]
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}This way i will iterate from 0 to myArray.length (not including) which is exactly all of the array indices.
Cheat sheet
Arrays store multiple values in a single variable. Each element has an index starting from 0:
let myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g']Access elements using square brackets with the index:
let myArray = [10, 20, 30, 40, 50]
let element = myArray[2] // Returns 30Iterate over arrays using .length property:
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}Try it yourself
function values(arr) {
// Write code here
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants11Arrays Part 1
Declaring an ArrayAccessing Array ElementsModifying ArraysArray Methods Part 1Array Methods Part 2Recap - Array Processor3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False