Undefined vs Not Defined in JavaScript
In JavaScript, the keyword undefined is used to indicate that a variable has been declared but not yet assigned a value. It is also used to indicate that a function doesn't return any value.
You must have seen undefined in the console whenever you execute something that doesn't return a value. Now you know why :D.
JavaScript assigns the value undefined to variables during the memory creation phase of an execution context. Until JS hasn't reached the line where the variable is initialized during the code execution phase, the variable holds the value undefined.
console.log(a);
var a = 10;
console.log(a);
Output
undefined
10
Assigning a variable undefined is JavaScript's way of recognizing the presence of the variable in the code, but not giving the variable it's assigned value until JS has reached that line of code execution i.e., if at all the variable is initialized at some point in the code. If we don't initialize the variable at all, it will have the value undefined throughout the entire program.
var a;
console.log(a);
Output
undefiend
undefiend doesn't imply empty or void.
It is considered a bad practice to assign a variable undefined manually. JS won't throw any error while doing so but it completely takes away the purpose of the keyword.
Not defined is when a variable hasn't been allocated memory in the first place.
This can happen when you don't decalre a variable and try to access it somewhere in the code.
var a = 10;
console.log(a);
console.log(b);
Output
10
Uncaught ReferenceError: b is not defined at <anonymous>
[anonymous refers to the global execution context]