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
instanceofoperator - Using
constructorproperty - Using
Object.prototype.toString()method