Unfortunately in JavaScript both objects and arrays have the typeof of 'object'
. In fact even the NULL value has the typeof of 'object'
, what makes things even worse. If you want to distinguish all those "wannabe-objects" existing in JS, you should use something like:
function smartTypeOf(x) {
if (typeof x !== 'object') return typeof x;
if (x === null) return 'null';
if (Array.isArray(x)) return 'array';
return 'object';
}
You may alternatively want to use instanceof instead, e.g.:
if (x instanceof Array) return 'array';
if (x instanceof Promise) return 'promise';
if (x instanceof YourCustomClassInstance) return 'yourcustomclassinstance'
By the way, if it ever happened that you have something being an object and want an array (it is not case here, thou!):
If the object is iterable, e.g. a Set
, or an arguments
instance:
var x = new Set([1, 2, 1]);
Array.from(x); // [1, 2]
If the object is any (non-NULL) object and you want array of its properties values or keys respectively:
var x = {a: 2, b: 4, c: 7};
Object.values(x); // [2, 4, 7]
Object.keys(x); // ['a', 'b', 'c']