Suggest an editImprove this articleRefine the answer for “Accessing a nonexistent index”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)If you access a **nonexistent array index**, JavaScript returns `undefined`, but no error occurs. **Key point:** however, if the array itself is `undefined`, accessing any index on it throws a `TypeError`.Shown above the full answer for quick recall.Answer (EN)ImageIf 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: | 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.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.