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 ?
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 ?
Check out Array.isArray() function:
Array.isArray(a);
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);
}
To return variable type of a use below
typeof(a)