3

I'm trying to check if a variable is an object like so:

if(obj && typeof obj === Object) {
    console.log('obj is an object and does not return null value');
}

what am i missing?

5 Answers 5

6

typeof returns a string representation of the type, but if you want to check for null then

if(typeof obj === 'object' && obj !== null) {
    console.log('obj is an object and does not return null value');
}
Sign up to request clarification or add additional context in comments.

3 Comments

@Jonatan Shahar: why using typeof and check for null. Best practice is using instanceof: From this book: books.google.com.vn/…
Note that this will return true for Arrays too. If you want a strict check that it's an Object you can use '[object Object]' == Object.prototype.toString.call(o).
Remember that functions are objects too and typeof on old versions of Safari sometimes returns 'function' on non-function objects. So you also need to test for typeof obj=='function'
0

Your code is fine, just replace Object with "object" string :)

Comments

0

It should be;

typeof obj === 'object'

The typeof operator uses strings as identifiers. You can read more about it on MDN.

Comments

0
'[object Object]' == Object.prototype.toString.call(obj)

Comments

0

the best way to do it is using instanceOf, best practice

if(obj instanceof Object) {
    console.log('obj is an object and does not return null value');
}

Comments