Skip to content
JavaScript: Reject holes before validating a numeric array

JavaScript: Reject holes before validating a numeric array

November 17, 2026

A sparse array can pass every(Number.isFinite) even though it has missing elements. Before adding numeric measurements, require an own value at each index and check that value.

Set up

Tested on Debian 13 Linux with Node.js v24.19.0. Use Bash, Node.js on your PATH, a text editor, and the mktemp, rm and rmdir utilities. No packages or network access are needed. Keep the same terminal through cleanup. Stop if setup fails before saving the source.

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Run the example

Save as javascript-reject-sparse-number-arrays.mjs:

import assert from 'node:assert/strict';

function validateMeasurements(values) {
  if (!Array.isArray(values)) throw new TypeError('Expected an array');
  for (let index = 0; index < values.length; index += 1) {
    if (!Object.hasOwn(values, index)) {
      throw new TypeError(`Missing measurement at ${index}`);
    }
    if (!Number.isFinite(values[index])) {
      throw new TypeError(`Invalid measurement at ${index}`);
    }
  }
  return values;
}

const sparse = [10, , 30];
console.log('every accepts sparse array:', sparse.every(Number.isFinite));
assert.throws(() => validateMeasurements(sparse), /Missing measurement at 1/);
for (const input of [[10, undefined], [NaN], [Infinity], ['10'], null]) {
  assert.throws(() => validateMeasurements(input), TypeError);
}
assert.deepEqual(validateMeasurements([]), []);
const complete = validateMeasurements([10, 20, 30]);
console.log('Complete total:', complete.reduce((sum, value) => sum + value, 0));
console.log('Missing and invalid measurements: rejected');

Run:

node javascript-reject-sparse-number-arrays.mjs

Observed output:

every accepts sparse array: true
Complete total: 60
Missing and invalid measurements: rejected

Validate positions as well as values

The ECMAScript every algorithm checks whether a property exists before calling the callback. An ordinary hole has no such property, so the callback never sees it. An array containing only holes can therefore pass the same predicate.

The indexed loop visits every position below length. Object.hasOwn also rejects an absent element supplied through the prototype chain, which is useful when the contract requires actual array entries. An explicit undefined has an own property but fails the finite-number check. Numeric strings are rejected rather than converted.

Define the remaining contract

The validator permits an empty array; the reduction starts at zero so that case has a defined total. Require a positive length if an empty batch is invalid. Set a maximum length before the loop when input size is not already bounded.

These checks target ordinary, stable arrays containing primitive numbers. Getters and proxies can execute code during reads, and another part of your program can mutate the returned array later. Validate plain data at a controlled boundary and copy it if ownership must change. Finite individual values can still overflow when summed, so check the calculated total separately if that matters to the application.

Clean up

Remove the saved file and empty scratch directory. If the directory is not empty, inspect its contents before removing anything else.

rm -- javascript-reject-sparse-number-arrays.mjs
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

Acknowledgements

This post was created with assistance from AI.

Last updated on