6

Is there a way for typeof to return what an object is?

typeof {};

returns "object"

typeof [];

also returns "object". Is there a way in js to return "array"?

On top of that, is there a way to tell if an object is a DOM object, a javascript object or whatever object?

Gundam Meister
  • 1,425
  • 2
  • 19
  • 29
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof Since everything is an object you have to play games to get further details. – Dave Newton Feb 23 '16 at 19:56
  • 3
    See [`instanceof`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) `[] instanceof Array` is `true` `({}) instanceof Array` is `false` This also applies to non-Array types. `document.body instanceof `[`Element`](https://developer.mozilla.org/en-US/docs/Web/API/Element) is `true` – arcyqwerty Feb 23 '16 at 19:57
  • If you really need to write code that checks whether a variable is a DOM element or a JavaScript object, you should probably ask why you're getting both in the same function in the first place. – Blazemonger Feb 23 '16 at 19:58
  • as @arcyqwerty mentioned, you can do it like in this fiddle: https://jsfiddle.net/gmjy3ybv/ – Icepickle Feb 23 '16 at 20:06

2 Answers2

5

You can't extend the typeof operator but for better type inspection you can (ab)use Object.prototype.toString

Object.prototype.toString.call([]) === '[object Array]'
Object.prototype.toString.call(document) === '[object HTMLDocument]`
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
  • 1
    This is a really inefficient solution. You should use [the `instanceof` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof). – Grant Gryczan Jun 09 '18 at 05:44
  • `instanceof` does not *return what an object is* so this is the only answer –  Jun 22 '19 at 00:35
3

You can use Array.isArray() for it.

The Array.isArray() method returns true if an object is an array, false if it is not.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392