What is the reliable way to check if a variable is an Array in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

What is the reliable way to check if a variable is an Array in JavaScript?

message-square
0

The reliable way to check if a variable is an Array in JavaScript is Array.isArray(value), which returns true if value is an array—even across different realms, <iframe> windows, or vm contexts—and false for plain objects, null, undefined, primitives, Set/Map instances, and arguments or NodeList array-like collections. Avoid typeof value === "object" (too broad, includes null and plain objects) and value instanceof Array (can fail across separate execution realms/iframes or modified prototype chains).


1. Using Array.isArray() for Reliable Cross-Realm Checks

Call Array.isArray(value) directly to test true array identity without mutating value or assuming a single realm:

// Non-mutating helper confirming whether a value is a true JavaScript Array
function isTrueArray(value) {
  return Array.isArray(value);
}

// Example usage:
console.log(isTrueArray([1, 2, 3]));          // true
console.log(isTrueArray([]));                 // true
console.log(isTrueArray({ length: 2 }));      // false (array-like object, not an Array)
console.log(isTrueArray(new Set([1, 2])));    // false
console.log(isTrueArray(null));               // false
  • Cross-realm safety: If an array originates inside an <iframe> or another realm, Array.isArray() still returns true whereas instanceof Array can return false.
  • Excludes array-like objects: Strings, arguments, NodeList, and { 0: "a", length: 1 } have .length, yet Array.isArray() accurately returns false.

2. Why typeof and instanceof Array Fall Short

Understanding why common alternatives fail prevents subtle bugs when handling untrusted data, cross-frame values, or collections:

// Compare Array.isArray() against common pitfalls on sample values
function inspectArrayChecks(value) {
  return {
    arrayIsArray: Array.isArray(value),
    typeofValue: typeof value,
    instanceofArray: value instanceof Array
  };
}

// Example usage:
console.log(inspectArrayChecks(["a", "b"]));
// { arrayIsArray: true, typeofValue: "object", instanceofArray: true }
console.log(inspectArrayChecks(null));
// { arrayIsArray: false, typeofValue: "object", instanceofArray: false }
  • typeof [] === "object": Arrays have typeof equal to "object", just like plain objects, Date, RegExp, and null.
  • value instanceof Array: Relies on Array.prototype in the current realm; can fail when values cross iframe boundaries or use custom prototypes.

3. Safe Non-Mutating Array Guards in Callbacks and Pipelines

Always guard array operations with Array.isArray() before calling .map(), .filter(), .reduce(), or .length on external inputs such as parsed JSON or API responses:

// Safely map over an input only when it is an Array, returning [] otherwise
function safeMapArray(maybeArray, mapperFn) {
  if (typeof mapperFn !== "function") {
    throw new TypeError("Expected mapperFn to be a function.");
  }

  if (!Array.isArray(maybeArray)) {
    return [];
  }

  return maybeArray.map((item, index, arr) => mapperFn(item, index, arr));
}

// Example usage:
console.log(safeMapArray(["a", "b"], (s) => s.toUpperCase())); // ["A", "B"]
console.log(safeMapArray({ a: 1 }, (s) => s));                 // []
  • Prevent runtime crashes on bad payloads: APIs sometimes return an error object or null instead of an expected list; checking Array.isArray() avoids TypeError: ...map is not a function.
  • Convert array-likes explicitly when intended: If you genuinely want an array from a Set or NodeList, use Array.from(iterable) rather than treating the original object as an Array.

TL;DR: Use Array.isArray(value)—it reliably detects true arrays across realms/iframes and returns false for null, plain objects, Set/Map, and array-like objects where typeof and instanceof Array can mislead or fail.