Home » Programming » Javascript » Javascript isArray() function

Javascript isArray() function

posted in: Javascript, Programming 0

Javascript does not provide a function to recognize if a variable is an array or not; you can make a “typeof” of the variable however u’ll get an ‘object’ datatype, as in the following code
[sourcecode language=”javascript”] var myarray = [1, 2, 3];
var myobject = { key: ‘value’ };
alert(typeof myarray); //return ‘object’
alert(typeof myobject); //return ‘object’

to recognize a data type ‘object’ from ‘array’, you need a specialized function like this…
[sourcecode language=”javascript”] function isArray(value){
var b = typeof value;
if(b === ‘object’){
b = (typeof value.length === ‘number’ &&
!(value.propertyIsEnumerable(‘length’)) &&
typeof value.splice === ‘function’) ? true : false;
b = false;
return b;
var myarray = [1, 2, 3];
var myobject = { key: ‘value’ };
alert(isArray(myarray)); //return true
alert(isArray(myobject)); //return false

Good work!
Max 🙂

Leave a Reply

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