Skip to content

Instantly share code, notes, and snippets.

@fmartins-andre
Created July 26, 2023 14:59
Show Gist options
  • Save fmartins-andre/86b6a3e437bc5d3799bd0e00eb251a16 to your computer and use it in GitHub Desktop.
Save fmartins-andre/86b6a3e437bc5d3799bd0e00eb251a16 to your computer and use it in GitHub Desktop.
How to differ objects in JavaScript

To check what the real type of and variable, run this command:

  Object.prototype.toString.call(myVar)

It'll return something like [object Object]. The second word is the real type of the variable.

Some examples:

  console.log(Object.prototype.toString.call(null)) // returns [object Null]
  console.log(Object.prototype.toString.call(undefined)) // returns [object Undefined]
  console.log(Object.prototype.toString.call([])) // returns [object Array]
  console.log(Object.prototype.toString.call(new Date())) // returns [object Date]
  console.log(Object.prototype.toString.call({})) // returns [object Object]
  console.log(Object.prototype.toString.call(new Error('error'))) // returns [object Error]
  console.log(Object.prototype.toString.call(/\D/)) // returns [object RegExp]
  // ... and so on...

To check if a variable is an object, you can use something like:

  if(Object.prototype.toString.call(myVar).endsWith('Object]')) {
    // do something
  }

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment