DEV Community

Cover image for Undefined Vs Not defined in javascript...
Jasmeet Singh Bali
Jasmeet Singh Bali

Posted on

Undefined Vs Not defined in javascript...

  • Whenever we define a variable then the execution context in the first phase i.e memory allocation phase will provide a placeholder named as undefined to that variable

    • Not defined is error thrown out by the JS Engine when we are trying to access any variable that has not been assigned any memory by the execution context

                # code snippet-4
                console.log(a); // undefined (for the memory allocation phase)
                var a = 7;
      
                console.log(x); // not defined
                console.log(a); // 7 (after code execution phase)
      

Important Conclusions/Takeaways

  • for the code snippet-4 the line console.log(a); represents hoisting in javascript that means accessing variable before they are defined, and the reason why a hoisted variable gives undefined as output is because of the execution context memory allocation phase as every javascript program on execution will create a memory even before the actual execution of the javascript code happens. If you want to understand what execution context is then refer my Execution Context Article

  • An Interesting thing to note is that the state of the variable changes from undefined to not undefined if we have initialized some value to it or provided some value to it in later part of the code

                  # code snippet-5
                  var a;
                  console.log(a); //undefined
                  a=10;
    
                  if(a===undefined){
                    consle.log("a is undefined");
                  }
                  else{
                    console.log("a is not undefined");
                  }
    
                  # output:
    
                  undefined
                  // for uninitialized variable a
    
                  a is not undefined
                  // after initializing variable a as 10
    

You My Friend Have A Great Day!!

Top comments (0)