typeof operator- typeof null-a known bug in javascript

tn500w_javascript-logo

typeof operator- typeof null-a known bug in javascript

As per ECMAscript5 specifications Javascript has 5 primitive data-types.

  • number
  • string
  • boolean
  • undefined
  • null

We all know that Javascript is loosely typed, a Javascript variable holding a particular type of value can hold another type of value at another point of time. So, interrogating Javascript variables and values is a very handy feature in Javascript. This can be done by typeof operator.

typeof <value>;
typeof <variable>;

Now let’s do an example.

var anoop;
console.log(typeof anoop); //prints undefined
anoop=2;
console.log(typeof anoop); //prints number
anoop="hello";
console.log(typeof anoop); //prints string
anoop=true;
console.log(typeof anoop); //prints boolean
anoop=null;
console.log(typeof anoop); //prints object. What????????????

Everything was going fine, things got tricky when we encountered typeof null. This should ideally be null as null is a data-type. Don’t get confused by listening to reasons for it. This is a bug, typeof null should result null as null is a primitive data-type.People who developed Javascript accept it as a bug in the initial implementation, and could not fix it in the later versions as it could break older codes which depends on this behavior.

About Anoop Kumar Rai