How to Check if a Value is an Object in JavaScript

how-to-check-if-a-value-is-an-object-in-javascript

Using typeof operator

JavaScript provides the typeof operator to check the value data type.

The typeof operator returns a string indicating the type of the operand’s value.

typeof variable === 'object' returns true for:

  • objects
  • null
  • arrays
  • regular expressions
  • new Date()
  • new Map()
  • new Set()

So these validation are required.

code

const isObject = (value) => {
  return typeof value === 'object'
  && value !== null
  && !Array.isArray(value)
  && !(value instanceof RegExp)
  && !(value instanceof Date)
  && !(value instanceof Set)
  && !(value instanceof Map)
}

There are also other strategies to check if a value is an object like:

  • Using instanceof operator
  • Using constructor property
  • Using Object.prototype.toString() method
Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
my-process-for-writing-laravel-packages

My process for writing Laravel packages

Next Post
ci/cd-part-1:-unit/integration-testing

CI/CD Part 1: Unit/Integration Testing

Related Posts