Check if variable is array in JavaScript

The JavaScript isArray method is a built-in array method that allows you to check whether a given value is an array. It returns true only if the value is an array and returns false if it is not. ES5 version of Javascript introduced this feature.

Syntax

The syntax for using the isArray method is as follows.

Parameter

Here, value is the variable or expression you want to check whether it’s an array. The isArray returns true if the value is an array and false otherwise.

IsArray Example

The code below checks various arrays, and the result is always true.

Returns false for non-arrays and array-like objects.

isArray vs. InstanceOff

We can also use instanceof to check whether the variable is an array. But both use different techniques to check for an array.

The instanceOf check if an object is an instance of a particular class or constructor function. Due to this, instanceof can give false negatives if you’re checking arrays created in other frames or windows.

You can see from the code below that instanceOf fails to detect an array that we created in a different iframe.

Hence it is better to use array.isArray() rather than instanceof because it works across realms.

Summary

  • The isArray method allows us to check whether a given value is an array.
  • isArray method was introduced in ES5 version of Javascript. If you are using prior version, then use instanceOf.
  • The instanceOf operator fails to detect arrays created in different iframe.

Reference

IsArray

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top