Skip to main content

Command Palette

Search for a command to run...

🔥 How to check if something is an array in JavaScript

Published
•1 min read

Internally, there is no type called “array” in JavaScript. When used on an array, typeof returns "object" instead.

To check if something is an array, use Array.isArray() instead.

// `typeof` an array returns “object” because JS has no type called “array”.
typeof ['a', 'b', 'c']                     // ⇒ "object"

// The array is treated like this equivalent object.
typeof { 0: 'a', 1: 'b', 2: 'c' }          // ⇒ "object"

// Use `Array.isArray` instead of `typeof` to test if something is an array.
Array.isArray(['a', 'b', 'c'])             // ⇒ true
Array.isArray({ 0: 'a', 1: 'b', 2: 'c' })  // ⇒ false
P

In modern browsers you can do:

Array.isArray(obj)

For backward compatibility you can add the following:

// only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
  Array.isArray = function(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
  }
};
P

In modern browsers you can do:

Array.isArray(obj)

For backward compatibility you can add the following:

// only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
  Array.isArray = function(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
  }
};