How do I check if value is an Array?
Monday, August 10, 2020
How do I check if value is an Array?
tldr;
Use the Array.isArray()
method to determine if a value is an Array in JavaScript.
But, why?
Not all arrays are of the same Array.prototype
to avoid multiple frames from mutating the same prototype. You can read the full details here, but let's look at a quote from the article:
The shared-mutation hazard of having arrays in two coordinating windows be instances of the same Array constructor, sharing the same Array.prototype, is enormous when either page augments Array.prototype (not to mention the security problems when one page is malicious!), so Array and Array.prototype in each window must be different. Therefore, by the semantics of instanceof, o instanceof Array works correctly only if o is an array created by that page's original Array constructor (or, equivalently, by use of an array literal in that page). Pfui.
While we might consider this a bug in the ECMAScript language the intention is to prevent malicious code between frames. Therefore, we cannot reliably expect instanceof
to evaluate whether an object is an array, primarily if the array is created by another frame's Array
constructor function.
Let's look at an example that will not work:
const i = document.createElement('iframe');
document.body.appendChild(i);
const newIFrameArray = new window.frames[0].Array();
console.log(newIFrameArray instanceof Array); // 🛑 false
console.log(newIFrameArray instanceof window.frames[0].Array); // ✅ true
Let's break this down line by line:
- First, we create a new
iframe
element. - Next, we append the new
iframe
element to the current document'sbody
. - Then, using the new frame's
Array
constructor we create a new array instance using the constructor function. - The first console log will output
false
because thenewIFrameArray
is not an instance of the current window'sArray
prototype. - The second console log will output
true
because thenewIFrameArray
is an instance of the iframe's windowArray
prototype.
The conclusion is that to deterministically check if a value (object) is an array we should use the Array.isArray()
static method.
Instructions
use Array.isArray()
for determining if an object is an array
using instanceof
for determining if an object is an array
Code Examples
use Array.isArray()
to deterministically check if an object is an array
const a = [];
const b = Array.isArray(a);
avoid instanceof Array
when checking if an object is an array
const a = [];
const b = a instanceof Array;
Have a question or comment?