March 14, 2018
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
[],new Array()should be considered as anarrayundefined,{},'',{length:1}shouldn't be considered as anarray
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

Comments
Nothing yet. Say the first thing.
Sign in to join the conversation.