DEV Community

Dom Habersack
Dom Habersack

Posted on • Originally published at islovely.co

🔥 How to check if something is an array in JavaScript

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
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
eliabe45 profile image
Eliabe França

I've always used instaceof

Collapse
 
brandonmweaver profile image
Brandon Weaver

This is more readable in my opinion.
[0] instanceof Array; // true

Collapse
 
domhabersack profile image
Dom Habersack

That is a decent alternative. It could cause issues when working with multiple frames, because each context has its own Array object:

developer.mozilla.org/en-US/docs/W...

When working with iframes, Array.isArray() gives you more accurate results. When working with a single context, instanceof is fine.

Collapse
 
seyeolajuyin profile image
Seye Olajuyin

I had no idea this exists. Thank you!