How do you check if a value is an object in JavaScript?
Method 1: Using the typeof operator The typeof operator returns the type of the variable on which it is called as a string. The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”.
Use the typeof operator to check the type of a variable in TypeScript, e.g. if (typeof myVar === 'string') {} . The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.
If typeof yourVariable === 'object'
, it's an object or null
.
If you want null
, arrays or functions to be excluded, just make it:
if ( typeof yourVariable === 'object' && !Array.isArray(yourVariable) && yourVariable !== null ) { executeSomeCode(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With