Simple function to detect Array in JavaScript

JavaScript doesn’t really separate Arrays from Objects. In other words, if you check typeof for something like { red:44, green:57, blue:220 } or [44, 57, 220], they both return “object”, even though the second one is an Array (the two are similar but not exactly the same, for example, you can’t access the “red” value of the object via index 0). So I needed a quick way to detect array as opposed to an object and came up with this short function.

function istype(obj) {
	return (typeof obj !== 'object' || typeof obj[0] === 'undefined')
		? typeof obj
		: 'array';

GitHub Mark istype.js gist on GitHub

Be the first to comment on this post

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>