0

Is there some specific reason behind keeping null an object type in JavaScript? I have a lot of type-checking in my code and I would like to know the reason/explanation behind it, so I can clear out the confusion. Like

var bar = null;
console.log(typeof bar === "object");  // logs true!

In this case, what if bar was a function variable that returns an 'object'? Desired behaviour is that it should return true, but it actually return false.

var bar = function(){return {foo : 'bar'}};
console.log(typeof bar === "object");  // logs false!
ronakshah725
  • 250
  • 2
  • 9
  • At this point, it's probably not being changed for backwards compatibility reasons. As for why it was originally done this way, you'd have to ask one of the original designers. – jfriend00 Aug 10 '15 at 17:05
  • Mostly because NULL is a value. It's not blank or zero. It's NULL. It is a valid testable value. – durbnpoisn Aug 10 '15 at 17:05
  • It is not object, it is [primitive](http://es5.github.io/#x4.3.2). This is just a preserved legacy bug in `typeof`. – Teemu Aug 10 '15 at 17:05
  • `bar` is a function, you are not testing what it returns. so a function is not an object, hence false – epascarello Aug 10 '15 at 17:05
  • Did you mean to do: `console.log(typeof bar() === "object");` where you actually execute `bar()` to check `typeof` the return value? – jfriend00 Aug 10 '15 at 17:08
  • check this answer http://stackoverflow.com/questions/801032/why-is-null-an-object-and-whats-the-difference-between-null-and-undefined – Laky Aug 10 '15 at 17:08
  • @epascarello Correct! When I do typeof bar, it will not execute the function and get an object, it will just get function type. My bad! – ronakshah725 Aug 10 '15 at 17:09

0 Answers0