Access Array Elements in JavaScript
12 min read·Jan 1, 2025
Each element of an array is associated with a unique numerical key called an index, which represents its position within the array.
The 1st element of the array is located at index 0, the 2nd element at index 1, and so on.
To access the value stored at a specific index, you can use the following syntax:
array[index]
Where:
arrayis an array instance.indexis either a user-defined number, a variable containing a number, or a computed number.
Note: When trying to access a non-existent array index, the returned value will be
undefined.
Example
Let's consider this script:
const rgb = [255, 192, 203];
console.log('red = ', rgb[0]);
console.log('green = ', rgb[1]);
console.log('blue = ', rgb[2]);
When executed, it will:
- Declare a variable named
rgband initialize it with an array containing 3 integer values. - Output the value of the 1st element located at index
0. - Output the value of the 2nd element located at index
1. - Output the value of the 3rd element located at index
2.
Which will produce this output:
red = 255
green = 192
blue = 203
Get the array length
In JavaScript, arrays are in fact built-in objects with a predefined list of properties and methods.
To get the number of elements in an array (its length), you can use the length property of the array instance as follows:
array.length
Example
Let's consider this script:
const cardinalPoints = ["North", "East", "South", "West"];
console.log(cardinalPoints.length);
When executed, it will:
- Declare a variable named
cardinalPointsand initialize it with an array containing 4 strings. - Output the number of elements present in the
cardinalPointsarray using itslengthproperty.
Which will produce this output:
4
Access subarray elements
To access and use the value stored at a specific index, you can use the following syntax:
array[indexA][...][indexN]
Where:
indexAis the index of the array within the main array.indexNis the index of the element within the nth nested array.
Note: The following expression will return the entire nested array:
array[index]
Example
Let's consider this script:
const board = [
[' ', ' ', ' '],
['o', 'x', 'x'],
['o', ' ', ' ']
];
console.log(board[1][2]);
When executed, it will access the value of the third element of the second subarray contained in the board array.
Which will produce this output:
x
Browse arrays using a for loop
The first way to loop on the elements of an array is to use a for loop combined with the length property:
for (let index = 0 ; index < array.length ; index++) {
// array[index]
}
Where index is a computed variable incremented at each iteration for as long as it is inferior to the number of elements in the array.
Note: It's important to remember that array indexes start at
0and not1!
Example
Let's consider this script, that checks if the values of an array are sorted in ascending order:
function isArraySorted(array) {
if (!array) {
return false;
} else if (array.length === 1) {
return true;
}
for (let index = 0 ; index < array.length - 1 ; index++) {
if (array[index] > array[index + 1]) {
return false;
}
}
return true;
}
const isSorted = isArraySorted([1, 3, 5, 7]);
console.log(isSorted ? 'The array is sorted' : 'The array is not sorted');
When executed, the isArraySorted function will:
- Return
falseif thearrayparameter isnullorundefined. - Return
trueif the array contains only 1 element. - Loop on each element of the array, from index
0to its length - 1 (excluded), as the expressionarray[index + 1]would otherwise exceed the bounds of the array, resulting in an error. - Return
falseif the value of the current elementarray[index]is superior to the next elementarray[index + 1]. - Return
trueotherwise.
Which will produce this output:
The array is sorted
Browse arrays using a for...of loop
To directly iterate over the elements of an array rather than its indexes, you can use the for...of loop as follows:
for (let element of array) {
// element
}
Where element is the value of the current array element browsed by the loop.
Note: Unlike the
forloop, thefor...ofloop will automatically terminate when there are no more elements in the array.
Example
Let's consider this script, that searches for the biggest value in an array:
function findMaxNumber(array) {
if (!array) {
return null;
}
let max;
for (let value of array) {
if (max === undefined || max < value) {
max = value;
}
}
return max;
}
const max = findMaxNumber([3, 12, 5, 8]);
console.log('The biggest number is ', max);
When executed, the findMaxNumber function will:
- Return
nullif thearrayparameter isnullorundefined. - Declare a local undefined variable named
maxused to store the future maximum value of the array. - Loop on the value of each element of the array.
- Set the current value of the
maxvariable as the new maximum if the maximum isundefinedor inferior to the current value. - Return the
maxvariable containing the biggest value.
Which will produce this output:
The biggest number is 12
Enjoying the courses?
I've made these courses completely free so anyone can learn from them. If they've helped you and you'd like to actively support the work behind BackendBrewery, you can leave a tip:
Support BackendBrewery