Better Array check with Array.isArray

Samantha Ming
Jun 3 · 3 min read
CodeTidbit by SamanthaMing.com
const books = ['📕', '📙', '📗'];// Old way
Object.prototype.toString.call(books) === '[object Array]';
// ✅ Better
Array.isArray(books);

Array is not a true array

Let’s see what I mean by this, array is not a true array.

const array = [];typeof array; // 'object'

Array.isArray Demo

Alright, let’s try this method on other values and see what we get 👩‍🔬

These are all arrays, and will return true

// Empty Array
Array.isArray([]); // true
// Array
Array.isArray(['📓']); // true
// Array Constructor
Array.isArray(new Array('📓')); // true

These are NOT arrays, and will return false

// Object
Array.isArray({}); // false
// Object
Array.isArray({book: '📓'}); // false
// Number
Array.isArray(123); // false
// Boolean
Array.isArray(true); // false
// Boolean
Array.isArray(false); // false
// String
Array.isArray('hello'); // false
// Null
Array.isArray(null); // false
// Undefined
Array.isArray(undefined); // false
// NaN
Array.isArray(NaN); // false

instanceof vs Array.isArray

Another popular choice you might is using instanceof

const books = ['📕', '📙', '📗'];books instanceof Array; // true

But…

The problem is it doesn’t work with multiple contexts (e.g. frames or windows). Because each frame has different scopes with its own execution environment. Thus, it has a different global object and different constructors. So if you try to test an array against that frame’s context, it will NOT return true, it will return incorrectly as false.

Explanation in non-dev terms

You can think of frames like different planets. Every planet has its own system, with different gravity pull and composition. So instanceof only works on our planet, Earth. If you bring it to Mars, it won't work. However, with Array.isArray() it will work on any planet. It's universal. That's why you should use Array.isArray().

// Creating our new "planet" called mars
const mars = document.createElement('iframe');
document.body.appendChild(iframe);
xArray = window.frames[window.frames.length-1].Array;
// Let's make an array in our new "planet", mars
var marsArray = new xArray('👩', '👨');
// Using the instanceof tool to test the marsArray
marsArray instanceof Array;
// false --> ❌ doesn't work
// Now, let's try using our universal tool
Array.isArray(marsArray)
// true --> ✅ great, it works!

Community Input

if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ⇒ do not attempt to process array
} else {
// ⇒ process array
}


DailyJS

JavaScript news and opinion.

Samantha Ming

Written by

Front End Developer 👩‍💻 I love learning new things and sharing them with my community. Follow me to catch my weekly code tidbits 🔥

DailyJS

DailyJS

JavaScript news and opinion.