Check if object is an array in plain javascript

JavaScript is a dynamic language. At times, you might want to determine whether the object variable you're receiving is an Array or not. Usually, I use Lodash's _.isArray() for this. For a change, I explored other options, using plain JavaScript.

I learnt that there are 3 methods to do this.

Test inputs & results

  1. [], new Array() should be considered as an array
  2. undefined, {}, '', {length:1} shouldn't be considered as an array

1. Using ES5

You can use ES5 Array.isArray() to check whether a variable is an array or not

2. Using Object's toString()

toString() returns the string representation of the object. Calling toString on an Array gives us [object Array]

3. Using constructor and instanceof

Note: You can't use typeof since typeof arrayVariable will give you an object


For my new posts, Subscribe via weekly RSS, common RSS or Subscribe via Email