Difference Between Null and Undefined?

javascript Aug 09, 2019

A variable is undefined only when the variable is declared but not assigned a value, or the variable has been
explicitly assigned the undefined value. A variable is null only when it has been assigned the null value. This
being the case, we can easily detect undefined and null variables as shown in the example. This makes null
useful for explicitly representing a no-value variable, rather than a not-yet-defined variable, for example, in a
function’s return statement.

var a;
var b = null;
if ( typeof a === 'undefined' ) {  
console.log( "Variable a is undefined" );
if ( a === null ) {  
console.log( "Variable a is null" );
if ( typeof b === 'undefined' ) { 
console.log( "Variable b is undefined" );
if ( b === null ) { 
console.log( "Variable b is null" );

The output is:
Variable a is undefined
Variable b is null

The typeof operator is used again as a more error-proof method of determining the type of a variable. The
typeof operator returns a string label for the variable type. The operator will return the string undefined for
any variable that is truly undefined

Neeraj Dana

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Angular, React, React-Native, Vue js, Machine Learning