How to Access Array Elements in JavaScript: Syntax and Examples
In JavaScript, you access array elements using
array[index] where index is the position of the element starting from 0. Use square brackets [] with the index number to get or set the element value.Syntax
To access an element in an array, use the array name followed by square brackets containing the index number.
- array: The name of your array.
- index: The position of the element, starting at 0 for the first element.
javascript
array[index]
Example
This example shows how to access and print elements from an array of fruits.
javascript
const fruits = ['apple', 'banana', 'cherry']; console.log(fruits[0]); // first element console.log(fruits[1]); // second element console.log(fruits[2]); // third element
Output
apple
banana
cherry
Common Pitfalls
Common mistakes include using an index that is out of range or forgetting that array indexes start at 0.
Accessing array[-1] or array[array.length] returns undefined.
javascript
const numbers = [10, 20, 30]; // Wrong: index out of range console.log(numbers[3]); // undefined // Correct: last element index is length - 1 console.log(numbers[numbers.length - 1]); // 30
Output
undefined
30
Quick Reference
| Action | Syntax | Description |
|---|---|---|
| Access first element | array[0] | Gets the first item in the array |
| Access last element | array[array.length - 1] | Gets the last item in the array |
| Set element value | array[index] = value | Changes the element at the given index |
| Out of range access | array[index] | Returns undefined if index is invalid |
Key Takeaways
Use square brackets with zero-based index to access array elements in JavaScript.
Array indexes start at 0, so the first element is at index 0.
Accessing an index outside the array length returns undefined.
Use array.length - 1 to get the last element's index.
You can also assign values to array elements using the same bracket notation.