0

If I have a variable var a, and I want to check if it is of type array I can either do

a.constructor === Array

or,

a instanceof Array

which is a better way and why ?

Avinash Sharma
  • 111
  • 1
  • 11

3 Answers3

0

Check out Array.isArray() function:

Array.isArray(a);
madox2
  • 49,493
  • 17
  • 99
  • 99
  • 1
    I am not looking for other methods I am just curious that what is the difference between these two and is there any drawbacks of one of them ? – Avinash Sharma Feb 02 '16 at 12:26
  • 2
    Well, StackOverflow is a question and answer site. When you ask for "how do I know if something is an array", then people will answer that. For your more specific question, also check the linked duplicate about `instanceof` vs `constructor`. – Thilo Feb 02 '16 at 12:28
  • @AvinashSharma Yes, the drawback is that while `Array.isArray()` *always* tells you if something is an array, both `a.constructor === Array` and `a instanceof Array` will fail in some cases ([see this for details](http://web.mit.edu/jwalden/www/isArray.html)). – Frxstrem Feb 02 '16 at 12:31
0
if(typeof a === 'object' && Array.isArray(a)) {
    //its array
}

UPDATE : the difference

var a = Object.create(Array.prototype);

alert(a instanceof Array);                       //TRUE
alert(a.constructor === Array);                  //TRUE  
if (typeof a === 'object' && Array.isArray(a)) { //FALSE 
    alert(true);
} 
else {
    alert(false);
}

but then you do

var a = new Array();  // or var a = [];  etc

alert(a instanceof Array);                       //TRUE
alert(a.constructor === Array);                  //TRUE  
if (typeof a === 'object' && Array.isArray(a)) { //TRUE 
    alert(true);
} 
else {
    alert(false);
}
Oxi
  • 2,918
  • 17
  • 28
-1

To return variable type of a use below

typeof(a)
ElGavilan
  • 6,610
  • 16
  • 27
  • 36