Accessing a nonexistent index
If you access a nonexistent array index, JavaScript returns
undefined,
but no error occurs.
Example:
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 errorWhy 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:
-
undefinedmeans "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:
javascriptconst arr = undefined; console.log(arr[0]); // TypeError: Cannot read properties of undefined
You can check whether an element exists like this:
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 elementExample with "holes" (empty slots):
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:
| Situation | Result | Error? |
|---|---|---|
| The index exists | returns the value | No |
| The index doesn't exist | undefined | No |
| The array doesn't exist | TypeError | Yes |
| Empty slot (hole) | undefined, but index in arr -> false | No |
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 readyA concise answer to help you respond confidently on this topic during an interview.