JAVASCRIPT: Difference between UNDEFINED and NULL

Javascript Undefined vs NULL

Many a times we often get confused on whats the difference between UNDEFINED and NULL.
undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value.
Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
Unassigned variables are initialized by JavaScript with a default value of undefined. JavaScript never sets a value to null. That must be done programmatically.

 

  • SheetalD

    ~Thanks, it cleared my confusion…!!!

    • Arun Kumar

      I can give you a better example.

      var a;

      alert(typeof(a));

      var b = null;

      alert(typeof(b));

      Running the above script will result in the following output:
      undefined
      object
      ——————————-
      From the preceding examples, it is very clear that undefined and null are two distinct types:
      undefined is a type itself (undefined) while null is an object

  • Sanjeev

    Thank u… u given me very short answer

  • JIL

    Thanks !!

  • Good explanation, typeof(null) returns object but it’s not an object. It’s a javascript primitive type, this is the conflict in language it self, may be corrected in future of version of JS.

    • Arun Kumar

      I can give you a better example.

      var a;

      alert(typeof(a));

      var b = null;

      alert(typeof(b));

      Running the above script will result in the following output:

      undefined

      object

      ——————————-

      From the preceding examples, it is very clear that undefined and null are two distinct types:

      undefined is a type itself (undefined) while null is an object

      • KSN

        No,null is not an object.It is bug(which,probably, won’t be fixed because it will break existing code) that a typeof null returns an object.Try ‘null instanceof Object’ and you’ll get the truth 😛 .

        • laxris

          Maybe is not a bug but a feature. Seriously…

          null === undefined // false
          null == undefined // true
          null === null // true
          If you get my point.

        • AhammadaliPK

          I can’t agree with you , cause typeof and instanceof are different.The typeof operator returns a string indicating the type of the unevaluated operand , while The instanceof operator tests whether an object in its prototype chain has the prototype property of a constructor. Means , null is not an instance of class called object. It is not a bug.