HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Typechecking JavaScript arrays with Array.isArray()

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascripttypecheckingisarraywitharraysarray

Problem

To determine if an object is an array, you can either use Array.isArray() or the instanceof operator. While both methods work for arrays created either using the array literal syntax or the Array constructor, there's a key difference. Array.isArray() is more reliable, as it works with cross-realm-objects, such as those created in an iframe.
As illustrated in the previous example, instanceof breaks when working with an iframe. However, Array.isArray() produces the correct result regardless of the way the array was instantiated.
If you are interested in knowing why instanceof Array doesn't work across different globals (i.e. iframe or window), you can read more about it here.

Solution

let iframeEl = document.createElement('iframe');
document.body.appendChild(iframeEl);
iframeArray = window.frames[window.frames.length - 1].Array;

let array1 = new Array(1,1,1,1);
let array2 = new iframeArray(1,1,1,1);

console.log(array1 instanceof Array);   // true
console.log(Array.isArray(array1));     // true

console.log(array2 instanceof Array);   // false
console.log(Array.isArray(array2));     // true


If you are interested in knowing why instanceof Array doesn't work across different globals (i.e. iframe or window), you can read more about it here.

Code Snippets

let iframeEl = document.createElement('iframe');
document.body.appendChild(iframeEl);
iframeArray = window.frames[window.frames.length - 1].Array;

let array1 = new Array(1,1,1,1);
let array2 = new iframeArray(1,1,1,1);

console.log(array1 instanceof Array);   // true
console.log(Array.isArray(array1));     // true

console.log(array2 instanceof Array);   // false
console.log(Array.isArray(array2));     // true

Context

From 30-seconds-of-code: typecheck-array

Revisions (0)

No revisions yet.