Tip: Typechecking arrays with Array.isArray()

JavaScript, Type, Array · Nov 6, 2022

To determine if a JavaScript 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.

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

var array1 = new Array(1,1,1,1);
var 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

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.

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • Tips & Tricks

    Snippet collection

    A collection of quick tips and tricks to level up your coding skills one step at a time.

  • Collection is empty

    JavaScript, Type

    Checks if the a value is an empty object/collection, has no enumerable properties or is any type that is not considered a collection.

  • Value is promise-like

    JavaScript, Type

    Checks if an object looks like a Promise.

  • Value is array-like

    JavaScript, Type

    Checks if the provided argument is array-like (i.e. is iterable).