Skip to main content

Accessing a nonexistent index

If you access a nonexistent array index, JavaScript returns undefined, but no error occurs.


Example:

javascript
const arr = ["apple", "banana", "cherry"]; console.log(arr[0]); // "apple" console.log(arr[3]); // undefined - no such element console.log(arr[10]); // undefined - also without an error

Why this happens

  • In JavaScript, an array is an object, where indexes are string keys:

    javascript
    // roughly equivalent to const arr = { "0": "apple", "1": "banana", "2": "cherry", length: 3 };
  • If you access a nonexistent property, JS returns undefined (instead of throwing an error, like Python or Java would).


Important:

  • undefined means "the value is absent", not "an error".

  • But if you try to access an index on something that isn't an array at all (the array itself is undefined), then there will be an error:

    javascript
    const arr = undefined; console.log(arr[0]); // TypeError: Cannot read properties of undefined

You can check whether an element exists like this:

javascript
const arr = [1, 2, 3]; console.log(2 in arr); // true - the element at index 2 exists console.log(5 in arr); // false - no such element

Example with "holes" (empty slots):

javascript
const arr = [1, , 3]; // a skipped element console.log(arr[1]); // undefined console.log(1 in arr); // false (the slot doesn't actually exist)

That is: arr[1] gives undefined, but the slot itself doesn't exist - it's an empty slot, not equal to undefined.


In short:

SituationResultError?
The index existsreturns the valueNo
The index doesn't existundefinedNo
The array doesn't existTypeErrorYes
Empty slot (hole)undefined, but index in arr -> falseNo

Summary: Accessing a nonexistent array index returns undefined, but does not throw an error. This behavior is part of JavaScript's flexibility.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.