To check if a value exists at a specific index in a JavaScript array without mutating the array, verify that the index is a valid integer within bounds (Number.isInteger(index) && index >= 0 && index < array.length) and compare array[index] === targetValue (or Object.is(array[index], targetValue) when you also want NaN === NaN to evaluate as true). Simply checking array[index] === targetValue without bounds checking can still work for most values because out-of-range indices return undefined, but explicit bounds and input checks prevent subtle edge-case bugs with undefined elements, negative numbers, sparse arrays, or non-arrays.
1. Bounds-Checked Equality at a Specific Index
Validate that items is an array and index is a non-negative integer within items.length, then check whether the element at index matches targetValue:
// Non-mutating helper checking if targetValue sits at an exact valid array index
function hasValueAtIndex(items, index, targetValue, { strictNaN = true } = {}) {
if (!Array.isArray(items)) {
throw new TypeError("Expected items to be an array.");
}
if (!Number.isInteger(index) || index < 0 || index >= items.length) {
return false;
}
const actualValue = items[index];
if (strictNaN) {
return Object.is(actualValue, targetValue);
}
return actualValue === targetValue;
}
// Example usage:
const steps = ["init", "validate", "persist"];
console.log(hasValueAtIndex(steps, 1, "validate")); // true
console.log(hasValueAtIndex(steps, 1, "init")); // false
console.log(hasValueAtIndex(steps, 5, undefined)); // false (out of bounds)
console.log(steps); // ["init", "validate", "persist"] (unchanged)
- Explicit bounds check (
0 <= index < items.length): Distinguishes an out-of-range index from an array whose slot actually holdsundefined. Object.is()vs.===:Object.is(NaN, NaN)istrueand distinguishes+0from-0, whereas===treatsNaN === NaNasfalse.
2. Checking If Any Defined Value Exists at an Index vs. a Specific Value
Sometimes you want to know whether a slot holds a non-undefined value (or a truthy/non-null value) at index, rather than matching a specific target value:
// Non-mutating helper checking whether index is in bounds and holds a defined value
function hasDefinedValueAtIndex(items, index) {
if (!Array.isArray(items)) {
throw new TypeError("Expected items to be an array.");
}
if (!Number.isInteger(index) || index < 0 || index >= items.length) {
return false;
}
return Object.prototype.hasOwnProperty.call(items, index) && items[index] !== undefined;
}
// Example usage:
const sparseOrPartial = ["first", , "third"];
console.log(hasDefinedValueAtIndex(sparseOrPartial, 1)); // false (hole / undefined)
console.log(hasDefinedValueAtIndex(sparseOrPartial, 2)); // true ("third")
- Sparse arrays and holes: An empty slot created by
new Array(3)or["a", , "c"]has no own property at index1and reads asundefined. - Avoid negative indices in bracket notation: Unlike
array.at(-1),array[-1]looks up the string property"-1"rather than indexing from the end of the array.
3. Comparing Index-Specific Lookup vs. Array-Wide Search (includes / findIndex)
Use index-based lookup when position matters; use .includes() or .findIndex() when you only care whether a value appears somewhere in the array:
// Non-mutating helper comparing exact-index match vs. anywhere-in-array match
function locateValue(items, targetValue, index) {
if (!Array.isArray(items)) {
throw new TypeError("Expected items to be an array.");
}
return {
atExactIndex: hasValueAtIndex(items, index, targetValue),
foundAnywhere: items.includes(targetValue),
firstIndex: items.findIndex((entry) => Object.is(entry, targetValue))
};
}
// Example usage:
const letters = ["a", "b", "a"];
console.log(locateValue(letters, "a", 2));
// { atExactIndex: true, foundAnywhere: true, firstIndex: 0 }
- Do not confuse
.includes(val, fromIndex)with exact-index equality: Passing a second argument to.includes(val, index)searches fromindexonward, not only atindex. - **Keep operations
