Accessing a non-existent array index
If you access a non-existent array index, JavaScript returns undefined and no error is thrown. This is not a bug but a consequence of arrays being objects, and reading a missing property of an object in JavaScript is always safe.
Theory
TL;DR
- Reading a non-existent index yields
undefined, no exception is thrown. - The reason: an array is an object, indexes are string keys, and a missing property returns
undefined. undefinedhere means "the value is absent", not "an error occurred".- A
TypeErrorappears only when the array itself does not exist:nullorundefined. - You can check for presence with
index in arrorObject.hasOwn(arr, index). - An empty slot (a hole) also yields
undefined, butinreturnsfalsefor it.
Quick example
const arr = ['apple', 'banana', 'cherry'];
console.log(arr[0]); // 'apple'
console.log(arr[3]); // undefined, there is no such element
console.log(arr[10]); // undefined, and again no errorNone of these reads stops the execution of the code.
Why it works this way
In JavaScript an array is an object in which indexes are string keys:
// roughly equivalent
const arr = { '0': 'apple', '1': 'banana', '2': 'cherry', length: 3 };When you access a non-existent property, JavaScript returns undefined instead of throwing, unlike Python with its IndexError or Java with ArrayIndexOutOfBoundsException.
The same holds for negative and fractional indexes: they simply become ordinary string keys that the object does not have.
const arr = [1, 2, 3];
console.log(arr[-1]); // undefined, this is the key '-1', not "the last element"
console.log(arr[1.5]); // undefined
console.log(arr.at(-1)); // 3, this is how you take the last elementWhen you do get an error
undefined means "the value is absent", not "an error". But if you try to access an index of an array that does not exist at all, that is, the array itself is undefined or null, then you do get an exception:
const arr = undefined;
console.log(arr[0]); // TypeError: Cannot read properties of undefinedOptional chaining keeps such a read safe:
const arr = undefined;
console.log(arr?.[0]); // undefined, no error
console.log(arr?.[0] ?? 0); // 0, a default valueHow to check that an element exists
const arr = [1, 2, 3];
console.log(2 in arr); // true, the element at index 2 exists
console.log(5 in arr); // false, there is no such elementA more modern and safer alternative is Object.hasOwn():
console.log(Object.hasOwn(arr, 2)); // true
console.log(Object.hasOwn(arr, 5)); // falseThe check arr[i] !== undefined is not suitable here: it cannot tell a missing element from a stored undefined value.
const values = [1, undefined, 3];
console.log(values[1] !== undefined); // false, even though the element exists
console.log(1 in values); // trueAn example with holes (empty slots)
const arr = [1, , 3]; // a skipped element
console.log(arr[1]); // undefined
console.log(1 in arr); // false, the cell really is not thereSo arr[1] gives undefined, yet the slot does not exist: it is an empty cell, not a stored undefined value.
A short table
| Situation | Result | Error? |
|---|---|---|
| The index exists | returns the value | No |
| There is no such index | undefined | No |
The array does not exist (null or undefined) | TypeError | Yes |
| An empty slot (a hole) | undefined, but index in arr gives false | No |
Summary: accessing a non-existent array index returns
undefinedbut does not raise an error. That behaviour is part of the flexibility of JavaScript.
Common mistakes
- Expecting an exception, as in other languages. Going out of bounds is silent in JavaScript, so you will see the failure much later, already as an
undefined. - Confusing "no element" with "the value is
undefined". A comparison againstundefinedgives no answer; useinorObject.hasOwn(). - Using
arr[-1]as the last element. That is just the key'-1'; for the last element usearr.at(-1)orarr[arr.length - 1]. - Forgetting to check the array itself. If the data came from the network, the variable may be
undefined, and then the read throws aTypeError; guard it witharr?.[i]. - Chaining reads without a guard.
arr[10].namethrows aTypeError, becauseundefinedhas no properties; writearr[10]?.name. - Writing to a large index.
arr[100] = 1does not throw, it stretcheslengthto101and creates holes.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.