JavaScript – Access Elements of Array using Index

To access elements of an array using index in JavaScript, mention the index after the array variable in square brackets.

The syntax to access an element from array arr at index i is

</>
Copy
arr[i]

Read Array Element at Specific Index

array[index], if used in an expression, or on the right hand side of the assignment operator, fetches the element of the array at specified index.

In the following example, we take an array with three elements, and read the element at index 2.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <div id="output"></div>
    <script>
        var arr = ['apple', 'banana', 'cherry'];
        var element = arr[2];
        document.getElementById('output').innerHTML = 'arr[2] : ' + element;
    </script>
</body>
</html>

Update Array Element at Specific Index

array[index], if used on the left hand side of the assignment operator, updates the element of the array at specified index with the given value.

In the following example, we take an array with three elements, and update the element at index 2 with the value 'mango'.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <div id="output"></div>
    <script>
        var arr = ['apple', 'banana', 'cherry'];
        arr[2] = 'mango';
        document.getElementById('output').innerHTML = 'Array : ' + arr;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to access elements of an Array in JavaScript, with examples.