155k views
4 votes
What is a potential pitfall with using typeof bar === "object" to determine if bar is an object? How can this pitfall be avoided?

User CtrlX
by
8.1k points

1 Answer

1 vote

Final answer:

The potential pitfall with using typeof bar === "object" is that it will return true for arrays or null as well. To avoid this pitfall, use more specific methods such as Object.prototype.toString.call(bar) === '[object Object]' or bar instanceof Object.

Step-by-step explanation:

The potential pitfall with using typeof bar === "object" to determine if bar is an object is that it will return true for arrays or null as well. Arrays are technically a type of object, and null is considered an object in JavaScript. So, if you want to specifically check if bar is a non-null object, you should use typeof bar === "object" && bar !== null.

To avoid this pitfall, you can use more specific methods to check if an object is an instance of the Object constructor. For example, you can use Object.prototype.toString.call(bar) === '[object Object]' or bar instanceof Object. Both of these methods will only return true if bar is a non-null object.

User Eduardo Bezerra
by
8.4k points