Start learning free

LESSON 97 OF 410 · ARRAYS I

Accessing array elements in JavaScript

Lesson Read the full explanation

Arrays are ordered, meaning each element has a numbered position known as its index. We access an array element by referring to its index number.

Arrays use zero-based indexing, so the first element in an array has an index of 0, the second element has an index of 1, etc.

We’re using bracket notation ([]) with the index after the name of the array to access the element:

let myArray = ["Hello world!", 32, false];

console.log(myArray[0]); // Output: "Hello world!"
console.log(myArray[1]); // Output: 32
console.log(myArray[2]); // Output: false

Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    JAVASCRIPT · ARRAYS I

    Accessing Elements in JavaScript, explained

    Accessing Array Elements in JavaScript: Zero-Based Indexing Explained

    Every time you read a username from a list, display an item from search results, or loop over API data, you're accessing array elements. This is one of the most fundamental operations in JavaScript — and the zero-based indexing system trips up beginners more than almost anything else. Get this right and every loop, algorithm, and data structure you build will feel more natural.

    Zero-Based Indexing: The Mental Model

    Think of an array as a row of numbered boxes. The first box is numbered 0, not 1. The last box is numbered length - 1. Access any box with bracket notation: array[index].

    const scores = [95, 82, 74, 88, 91];
    //  indices:     0   1   2   3   4
    
    console.log(scores[0]);                    // 95  — first element
    console.log(scores[4]);                    // 91  — last element
    console.log(scores[scores.length - 1]);    // 91  — last element (any length)
    console.log(scores[5]);                    // undefined — out of bounds, no error
    

    Reading and Writing Elements

    Bracket notation works for both reading and updating elements in place:

    const tasks = ["Design", "Build", "Test"];
    
    // Read:
    console.log(tasks[1]);   // "Build"
    
    // Update (mutates the array):
    tasks[1] = "Develop";
    console.log(tasks);      // ["Design", "Develop", "Test"]
    
    // Dynamic index (computed at runtime):
    const i = 2;
    console.log(tasks[i]);   // "Test"
    

    Looping Over All Elements

    const prices = [29.99, 14.50, 89.99, 5.00];
    
    // Classic for loop — use when you need the index:
    for (let i = 0; i < prices.length; i++) {
      console.log(`Item ${i}: $${prices[i]}`);
    }
    
    // for...of — cleaner when you only need values:
    for (const price of prices) {
      console.log(price);
    }
    
    // forEach — functional style with index available:
    prices.forEach((price, index) => {
      console.log(`${index}: ${price}`);
    });
    

    Accessing the First and Last Elements

    const letters = ["a", "b", "c", "d", "e"];
    
    const first = letters[0];                     // "a"
    const last  = letters[letters.length - 1];    // "e"
    
    // Modern JavaScript — optional chaining for safety:
    const maybeEmpty = [];
    console.log(maybeEmpty[0]);                   // undefined (no error)
    

    Common Mistakes to Avoid

    • Off-by-one: The last valid index is length - 1, not length. arr[arr.length] returns undefined.
    • Starting at 1: If you write for (let i = 1; ...) you skip the first element. Start at 0.
    • Treating undefined as an error: Accessing an out-of-bounds index returns undefined silently — check your loop bounds if you're seeing unexpected undefined values.
    const arr = [10, 20, 30];
    
    console.log(arr[3]);    // undefined — NOT an error
    console.log(arr[-1]);   // undefined — JavaScript doesn't support negative indexing
    
    // Safe last-element access:
    console.log(arr[arr.length - 1]);   // 30
    console.log(arr.at(-1));            // 30 — modern ES2022 shorthand
    

    Key Takeaways

    • Arrays are zero-indexed: first element is at index 0, last at length - 1.
    • Use bracket notation arr[i] to read or write any element.
    • Accessing out-of-bounds returns undefined — JavaScript won't throw an error.
    • Use arr.at(-1) (ES2022) for the last element without computing length - 1.

    What to Learn Next

    Now that you can access individual elements, learn to work with slices using array.slice(start, end) for sub-arrays, and explore destructuring (const [first, second] = arr) for pulling out elements elegantly. Then combine indexing with loops and array methods like map() and filter() to transform entire collections in a single expression.

    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free