typeof bar === "object" to determine if bar is an object
typeof bar === "object" is a reliable way of checking if bar is an object
But:null is also considered an object!
Therefore:
var bar =null;console.log(typeof bar ==="object");// logs true!
Solution: also check if bar is null:
console.log((bar !==null) && (typeof bar ==="object"));// logs false
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: