Lesson 2: Accessing and Modifying Array Elements

Lesson Goal:

Learn how to read, change, and add elements in a JavaScript array using indexes. Understand how JavaScript handles undefined or invalid index access.


Accessing Elements in an Array

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.


Modifying Array Elements

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

Accessing Invalid or Empty Indexes

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"]

Try It Yourself

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);

Summary Table

ActionCode ExampleResult
Access an elementfruits[0]Returns first element
Change an elementfruits[1] = "pear"Updates second element
Add an elementfruits[3] = "grape"Adds new item at index 3
Access missing indexfruits[10]Returns undefined