DEV Community

Cover image for Understanding undefined, null, undeclared in Javascript
Shivaansh Agarwal
Shivaansh Agarwal

Posted on

Understanding undefined, null, undeclared in Javascript

  1. undefined

    • It's a primitive data type in Javascript.
    • Any variable which has been declared but has not been assigned any value has the value undefined. image
    • During the memory creation phase of the execution context, every variable is assigned the value of undefined by the JS Engine.
  2. null

    • It's a primitive data type in Javascript.
    • A variable can be assigned the value null.
    • Although null is itself a data type, but on checking it's type using typeof we get "object". image
    • Why is typeof null “object”?
  3. undeclared (not defined)

    • This occurs when we try to access a variable which hasn't been declared or initalized yet. image
    • If we try to console.log(undeclaredVar) the error will be raised as shown above, so especially for this a try{...} catch(e){...} block has to be written. But if we instead use "use strict" pragma we can fix these errors during compile phase itself rather than during runtime.
    • typeof operator is the only operator that can reference a variable that hasn't been declared and not throw an error. typeof undeclaredVar //"undefined"
  4. uninitialized (TDZ)

    • It was introduced with ES6.
    • It's based on the concept of Temporal Dead Zone.
    • Variables which are block scoped (declared using let or const) are initially uninitialized. They can't be accessed unless they're in the temporal dead zone or intialized. image

References & Further Reading:

  1. 6 ECMAScript Data Types and Values
  2. How to check if a variable is undefined versus it is undeclared in javascript?
  3. ECMAScript 5 Strict Mode, JSON, and More

Top comments (0)