Explain Codes LogoExplain Codes Logo

How do I check in JavaScript if a value exists at a certain array index?

javascript
index-out-of-bounds
javascript-basics
array-indexing
Nikita BarsukovbyNikita Barsukov·Nov 21, 2024
TLDR

Check a value's existence at a specified index in JavaScript using either the in operator or a comparison with the array's length:

Using in operator:

let exists = 1 in [1, 2, 3]; // true

Using length comparison:

let exists = 1 < [1, 2, 3].length; // true

To power-up your code, here are compact snippets using truthiness, or the hasOwnProperty method:

Truthiness:

let heroic = !![0, 1, 2][1]; // true, just like Hercules

hasOwnProperty method:

let heroic = [0, 1, 2].hasOwnProperty(1); // true, in JavaScript, we trust

Remember, Array indices start from Zero

Just a reminder, array indices in JavaScript starts at 0, meaning the first element is at index 0, and the last at array.length - 1. This is not a bug, it's a feature.

Prevent Index Out Of Bounds Error

Before proceeding with your Indiana Jones adventure in the array, validate that your index is within the valid range. Nonexistent indices ruins your day. In technical terms, 0 <= i < array.length.

Index adventure guard:

let isSafeIndex = (i, array) => i >= 0 && i < array.length;

The Existential Crisis Of Undefined Values

Even if the index is within range, it doesn't guarantee a non-undefined value. To avoid this existential crisis, we can use typeof.

Preventing crisis:

let crisisAverted = typeof array[index] !== 'undefined'; // Feels good, doesn't it?

Differentiating null and undefined values

Sometimes, you need to know if a value is neither null nor undefined. Strict vs Loose equality, the age-old JavaScript debate:

Null or undefined:

let isValue = array[index] != null; // Not afraid of ghosts

Non-empty array checks

Array indices shouldn't be checked if your array is pitch-black empty:

Array darkness check:

if (array && array.length) { // Feeling safe to go ahead }

Playing it smart & short

For code readability and brevity, a shorter check can be your go-to:

Short-n-sweet:

if (array[index]) { // Something valuable is here! }

Friendly warning: falsy values like 0, "", false, null, undefined, NaN would be considered non-existent.

A Peek into the Array

Assume we have a standard array ['🔑', '🔒', '💻', '📚', '📝'].

| Index | Value | | ----- | ----- | | 0 | 🔑 | | 1 | 🔒 | | 2 | 💻 | | 3 | 📚 | | 4 | 📝 | | 5 | ❌ |

Checking the existence of value at index 3 and 5:

let valueAtIndex3 = !!array[3]; // Getting our 📚 let valueAtIndex5 = !!array[5]; // Yikes! ❌

Going through the maze with Edge Cases

Sparse arrays may dodge your usual checks as they can have skips in the indices:

Sparse array example:

let trickyArray = []; trickyArray[10] = 'gold'; // Who put the gold so far?! console.log(0 in trickyArray); // false, ghost index! console.log(10 in trickyArray); // true, gold found!

While dealing with these sneaky sparse arrays, alternative arsenal like Object.keys() can save the day:

Alternative length check:

let realLength = Object.keys(sparseArray).length; // Counting the survivors

Wrapping up

Practice is the key to mastery, or so the wise old hermit said. If you found this helpful, upvote. Happy JavaScripting! 🚀