Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a value is an object in JavaScript

How do you check if a value is an object in JavaScript?

like image 367
Danny Fox Avatar asked Dec 14 '11 20:12

Danny Fox


People also ask

How do you check if the object exists 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”.

How do you check if a variable is an object in TypeScript?

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.


1 Answers

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(); }  
like image 110
Chuck Avatar answered Oct 16 '22 16:10

Chuck