Learn how to read, change, and add elements in a JavaScript array using indexes. Understand how JavaScript handles undefined or invalid index access.
You can access a specific item in an array using bracket notation with the element’s index.
let fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // Output: apple
console.log(fruits[2]); // Output: cherry
🔎 Remember: Array indexing starts at 0 — the first element is at index
0
.
You can overwrite an array element by assigning a new value to a specific index:
fruits[1] = "orange";
console.log(fruits); // Output: ["apple", "orange", "cherry"]
You can also manually add a new item at a specific index:
fruits[3] = "grape"; // Adds a new element at index 3
If you access an index that doesn’t exist yet, JavaScript will return undefined
:
console.log(fruits[10]); // Output: undefined
If you assign a value to a higher index without filling in the gaps, JavaScript inserts undefined
for missing elements:
let items = ["pen"];
items[3] = "notebook";
console.log(items); // Output: ["pen", undefined, undefined, "notebook"]
let cities = ["Berlin", "Paris", "Rome"];
// Access and print the second city
console.log(cities[1]);
// Change the third city to "Madrid"
cities[2] = "Madrid";
// Add a new city at index 3
cities[3] = "Vienna";
// Check the result
console.log(cities);
Action | Code Example | Result |
---|---|---|
Access an element | fruits[0] | Returns first element |
Change an element | fruits[1] = "pear" | Updates second element |
Add an element | fruits[3] = "grape" | Adds new item at index 3 |
Access missing index | fruits[10] | Returns undefined |