
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 jkoder;
console.log(typeof jkoder); //prints undefined
jkoder=2;
console.log(typeof jkoder); //prints number
jkoder="hello";
console.log(typeof jkoder); //prints string
jkoder=true;
console.log(typeof jkoder); //prints boolean
jkoder=null;
console.log(typeof jkoder); //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 that depend on this behavior.