CODE ARCHIVE

Years of coding.

Technical articles, programming tutorials, code snippets and source files shared over the years.

Back to all articles

ARTICLES

Javascript isArray() function

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

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...

function isArray(value){
	var b = typeof value;
	if(b === 'object'){
		if(value){
			b = (typeof value.length === 'number' && 
				!(value.propertyIsEnumerable('length')) && 
				typeof value.splice === 'function') ? true : false;
		}else{
			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 :)