CodeBlanks Logo Icon CodeBlanks

length and index relationship

JavaScript course · Beginner · Lesson 45/133

Learn the length property and how to access the last element.

Accessing the last element

You access the last element of an array with the index length - 1. In a three-element array length returns 3; the last element is arr[2].

Example: with const notes = [70, 85, 90];, notes[notes.length - 1] returns 90. This pattern keeps working when the array length changes.

Using length - 1 instead of a fixed index is safer; it still finds the last element after you add more elements.

Array bounds and undefined

Accessing an index outside the array bounds is not an error; JavaScript returns undefined. This is unlike most languages.

Example: with const items = ["a", "b"];, items[5] returns undefined. It does not crash the program.

So you must check whether an index is valid yourself. Negative indices also return undefined; items[-1] does not give the last element.

Exercise Print the last element of the scores array

Create an array named scores with at least four numbers. Then print scores[scores.length - 1] with console.log.

Show example solution
Define a scores array with four numbers, then print the last element with length - 1.
Example solution:
const scores = [10, 20, 30, 40];
console.log(scores[scores.length - 1]);

Test yourself

  1. When nums has four elements, what does nums[4] return?

    const nums = [10, 20, 30, 40];
    console.log(nums[4]);
    • 40
    • throws an error
    • null
    • undefined
    Show answer

    undefined — Correct. Out-of-bounds access returns undefined, not an error.

  2. Access the last element with length - 1

    const prices = [100, 200, 300];
    const last = prices[____];
    console.log(last);
    Show answer
    const prices = [100, 200, 300];
    const last = prices[prices.length - 1];
    console.log(last);
  3. Match expressions to values for <code>const nums = [10, 20, 30]</code>

    nums.length
    3
    nums[0]
    10
    nums[2]
    30
    nums[5]
    undefined

All lessons in Beginner