Search code examples
javascriptnullundefined

why undefined is a data type


I have learnt recently while debugging, that undefined is a data type and null is an object.

I think both of them comes under datatypes.

I checked the typeof undefined and typeof null. They returned "undefined" and "object" respectively.

typeof undefined 
"undefined"

typeof null
"object"

Could some body explain why is this strange behaviour.


Solution

  • typeof null being object is an early mistake - when they tried correcting it in a Chrome nightly (to typeof null === "null" ) too many things relied on the current behavior and too much code broke.

    JavaScript objects that are not set to normal values generally have three states:

    1. Undeclared.
    2. Undefined.
    3. Explicitly nothing.

    Undeclared

    For example - this case:

     y++; //I did not declare y before, this causes a reference error
     y === 'undefined'; //still a reference error 
     typeof y; //'undefined', since typeof is an operator and not a function.
    

    Basically, an undeclared variable is in the state 'the script does not know this variable'.

    Undefined

    This means that the the runtime 'knows this variable' but it wasn't set to anything yet. Or, as the language specification puts this:

    undefined value - primitive value used when a variable has not been assigned a value.

    For example:

     var y; //y is undefined
     y === undefined; //true, y defined the line above
     typeof y; //undefined, but this is redundant, just do `=== undefined`
     (function(x){ /* x is undefined here as it was set to nothing*/})()
    

    Explicitly nothing

    When you have something that is supposed to have a value but you want to declare that it is nothing. Or, as the language specification puts this:

    null value - primitive value that represents the intentional absence of any object value.

    For example, document.getElementById("foo"); returns null if the element with the given ID is not in the DOM to indicate explicitly nothing was returned. Constrast this with functions that have no return statements so they return undefined which is the default.