When a variable is declared, but no value is assigned to that variable then that variable will be of type undefined. For example,
var demoVar; console.log(demoVar);
The above code will output undefined to the console, since variable demoVar is declared but not assigned with a value.
Also, undefined is of type “undefined”.
var demoVar; console.log(typeof demoVar);
The above code will output “undefined” to the console.
NULL means lack of existence of a value. NULL value needs to be explicitly assigned to the variable. For example,
var demoVar = null; console.log(demoVar);
The above code will output null to console, since variable demoVar is manually assigned with null value.
Null can be considered as a placeholder value. A null value is assigned to variable to indicate that variable is empty at the current stage of program but will hold a value later on.
Unlike undefined, the type of null value is an object.
var demoVar = null; console.log(typeof demoVar);
The above code will output “object” to the console.
- Undefined means variable is declared but no value is assigned to that variable.
- NULL is a placeholder. It indicates that variable is intentionally assigned with an empty value.