Although typeof bar === “object” is a reliable way of checking if bar is an object, the surprising gotcha in JavaScript is that null is also considered an object!
Therefore, the following code will, to the surprise of most developers, log true (not false) to the console:
var bar = null; console.log(typeof bar === "object"); // logs true!
As long as one is aware of this, the problem can easily be avoided by also checking if bar is null:
console.log((bar !== null) && (typeof bar === "object")); // logs false
To be entirely thorough in our answer, there are two other things worth noting:
First, the above solution will return false if bar is a function. In most cases, this is the desired behavior, but in situations where you want to also return true for functions, you could amend the above solution to be:
console.log((bar !== null) && ((typeof bar === "object") || (typeof bar === "function")));
Second, the above solution will return true if bar is an array (e.g., if var bar = [];). In most cases, this is the desired behavior, since arrays are indeed objects, but in situations where you want to also false for arrays, you could amend the above solution to be:
console.log((bar !== null) && (typeof bar === "object") && (toString.call(bar) !== "[object Array]"));
Or, if you’re using jQuery:
console.log((bar !== null) && (typeof bar === "object") && (! $.isArray(bar)));
If you want to explore other questions about JavaScript, you can check our videos section! Below we have some examples:
You can also subscribe to some channels that broadcast in JavaScript, such as the following:
Another cool way to find out interesting things about JavaScript is to access our project page!
In 2024 we're witnessing a critical point in democratic technology: the integration of blockchain and…
We’re thrilled to announce an exciting opportunity for you to win not one but two…
Acquiring practical skills is crucial for career advancement and personal growth. Education Ecosystem stands out…
Artificial Intelligence (AI) has been making significant strides in various industries, and the software development…
Another week to bring you the top yield platforms for three of the most prominent…
If you hold a large volume of LEDU tokens above 1 million units and wish…
View Comments
Nice tip!
I need to keep this in mind!
That's a hard one :)