UNDEFINED Vs NOT DEFINED in JS
In JavaScript, understanding difference between undefined and not defined can be crucial.
JavaScript code execution happens in two phases : MEMORY CREATION PHASE and CODE EXECUTION PHASE.
In memory creation phase , the JS skims through whole program and allocates memory to all the variables and functions in form of key value pairs. Initially JS gives a spatial value called "UNDEFINED" to the variables and in functions., the whole code of functions is stored.
After the creation phase, execution phase begins, it variables are assigned the original values by replacing undefined value.
UNDEFINED represents the value assigned to a variable during compilation phase if no other value is assigned to it.
var a;
console.log(a); // Output : undefined
a = 10 ;
console.log(a); // Output : 10
In the above code, we declared a variable a, but haven't assigned any value to it, so when we log it , the output will be undefined. This happens in memory creation phase where the variable is allocated undefined value to it.
When it comes to NOT DEFINED, it means that variable has not been declared at all and if we try to access such variables it throws ReferenceError.
console.log(x); //Output : ReferenceError: x is not defined
In the above case, the variable x has never been declared which results in reference error.
Conclusion :
The main difference between UNDEFINED and NOT DEFINED is :
A variable that has been declared but not assigned any value is UNDEFINED.
A variable which is not at all declared is NOT DEFINED.
Subscribe to my newsletter
Read articles from Vijaya Shree directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by