How to efficiently check if variable is Array or Object (in NodeJS & V8)? How to efficiently check if variable is Array or Object (in NodeJS & V8)? javascript javascript

How to efficiently check if variable is Array or Object (in NodeJS & V8)?


For simply checking against Object or Array without additional function call (speed).

isArray()

isArray = function(a) {    return (!!a) && (a.constructor === Array);};console.log(isArray(        )); // falseconsole.log(isArray(    null)); // falseconsole.log(isArray(    true)); // falseconsole.log(isArray(       1)); // falseconsole.log(isArray(   'str')); // falseconsole.log(isArray(      {})); // falseconsole.log(isArray(new Date)); // falseconsole.log(isArray(      [])); // true

isObject()

isObject = function(a) {    return (!!a) && (a.constructor === Object);};console.log(isObject(        )); // falseconsole.log(isObject(    null)); // falseconsole.log(isObject(    true)); // falseconsole.log(isObject(       1)); // falseconsole.log(isObject(   'str')); // falseconsole.log(isObject(      [])); // falseconsole.log(isObject(new Date)); // falseconsole.log(isObject(      {})); // true


All objects are instances of at least one class – Object – in ECMAScript. You can only differentiate between instances of built-in classes and normal objects using Object#toString. They all have the same level of complexity, for instance, whether they are created using {} or the new operator.

Object.prototype.toString.call(object) is your best bet to differentiate between normal objects and instances of other built-in classes, as object === Object(object) doesn't work here. However, I can't see a reason why you would need to do what you're doing, so perhaps if you share the use case I can offer a little more help.


If its just about detecting whether or not you're dealing with an Object, I could think of

Object.getPrototypeOf( obj ) === Object.prototype

However, this would probably fail for non-object primitive values. Actually there is nothing wrong with invoking .toString() to retreive the [[cclass]] property. You can even create a nice syntax like

var type = Function.prototype.call.bind( Object.prototype.toString );

and then use it like

if( type( obj ) === '[object Object]' ) { }

It might not be the fastest operation but I don't think the performance leak there is too big.