Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

Null vs Undefined in JavaScript

Null and undefined are primitive values in JavaScript. JavaScript uses them to indicate the no value or absence of any value. The difference between Null & Undefined is subtle and confusing. In this tutorial let us explore them

Null Vs Undefined

Null & undefined both point to no value or absence of any value. But there are a few differences between them

Definition

The value undefined means value is not assigned & you don’t know its value. It is an unintentional absence of value.

he value null indicates that you know that the field does not have a value. It is an intentional absence of value..

Take a look at the following person function which returns the person object. It has a property dateOfMarriage..

                            
function person(name,dateOfMarriage) {
    return { 
        name: name, 
        dateOfMarriage: dateOfMarriage
    }
}
 
 
                            
                        
                            
                        

The dateOfMarriage is not a required field. If the person is married, then the field will contain a value.

If the person is not married, then the dateOfMarriage field will not have any value. To represent no value we explicitly (or intentionally) set its value as null. That is how we use null. The absence of value is intentional. We need to set the value to null explicitly.

                            
let p = person("Colin Bower", null); //Null is set explicitly. Person is not married
 
 console.log(p);                     //{name: 'Colin Bower', dateOfMarriage: null}
 isMarried(p);                       // Not Married
  
  
  
 function person(name, dateOfMarriage) {
   return {
     name: name,
     dateOfMarriage: dateOfMarriage,
   };
 }
  
 function isMarried(p) {
   if (p.dateOfMarriage === null) {
     console.log("not married");
   } else {
     console.log("married");
   }
 }
 
                            
                        
                            
                        

To check whether the person is married or not we check if the value is null. If null he is married else not.

But what if no value is provided for dateOfMarriage as in the following example. In that case, JavaScript sets its value to undefined. When you encounter value undefined, it implies that you do not know whether the person is married or not.

                            
let p = person("Colin Bower");  //No Value is provided for dateOfMarriage
 
console.log(p); //{name: 'Colin Bower', dateOfMarriage: undefined}
 
isMarried(p);   //Dont know
 
 
function person(name, dateOfMarriage) {
  return {
    name: name,
    dateOfMarriage: dateOfMarriage,
  };
}
 
 
function isMarried(p) {
  if (p.dateOfMarriage === null) {
    console.log("not married");
  } else if (p.dateOfMarriage === undefined) {
    console.log("Dont know");
  } else {
    console.log("married");
  }
}
 
                            
                        
                            
                        

Note that JavaScript also allows us the set the value to undefined explicitly.

                            
let p = person("Colin Bower", undefined);  
 
                            
                        
                            
                        

Data Types

The data type of undefined value is undefined. The data type of null value is null.

But using typeof on a null variable shows it as an object. This is a very old bug in JavaScript

                            

let a
let b=null
 
console.log(typeof(a))   //undefined
console.log(typeof(b))   //object
 
                            
                        
                            
                        

Setting the value

JavaScript sets the value to undefined, when it expects a value but does not find one. But it never sets the variable to null. You need to set the value of null explicitly

For Example. JavaScript automatically sets the Uninitialized variable to undefined.

                            
let a
console.log(a)   //undefined
 
 
                            
                        
                            
                        

The following are some of the instances where a variable gets the value undefined

  1. Uninitialized variable
  2. Function argument that has not been supplied
  3. The return value of functions that don’t return a value
  4. Non-existing object Property
  5. Non-existing array elements

Falsy

Both null & undefined is falsy value in JavaScript. i.e. when we use them in a boolean expression they are coerced to false.

                            
   let a
  let b=null
 
  if (!a) console.log('false')        //false
  if (!b) console.log('false')        //false
  
 
                            
                        
                            
                        

But they are neither false nor true.

                            
  let a
  let b=null
 
  if (a==false) console.log('false')       
  if (a==true) console.log('true')       
 
  if (b==false) console.log('false')       
  if (b==true) console.log('true')    
  
 
                            
                        
                            
                        
                            
console.log(true && null)   //null
console.log(true || null)   //true
 
 
console.log(true && undefined)   //undefined
console.log(true || undefined)   //true
 
                            
                        
                            
                        

Comparing Null with undefined

Comparing null with undefined results in different results depending on whether you use an equality checker (==) or strict equality checker (===)

null and undefined both represents no value hence equality checker (==) returns true. This is because the equality checker does not check for data type

                            
 console.log(null == undefined)      //true
 
                            
                        
                            
                        

But strict equality checker returns false because it also checks for the data type.

                            
console.log(null === undefined)      //false

    

    

Arithmetic Operations

In arithmetic operations undefined is coerced to NaN.

                            
let a=10
let b
 
console.log(a+b)        //NaN
console.log(Number(b))  //NaN
                            
                        
                            
                        

Null is coerced to 0.

                            
let a=10
let b=null
 
console.log(a+b)        //10
console.log(Number(b))  //0
console.log(a*b)        //0
 

    

    

TypeOf

The Typeof Operator returns the data type of the variable. It returns the data type of undefined correctly but returns “object” as the data type of null. This is a well-known bug in JavaScript.

                            
let a
let b=null
 
console.log(typeof(a))   //undefined
console.log(typeof(b))   //object
                            
                        
                            
                        
                            
let a=10
let b=null
 
console.log(a+b)        //10
console.log(Number(b))  //0
console.log(a*b)        //0
 

    

    

Null literal & Undefined global variable

Null is literal in JavaScript. It is used to represent null. We use that to compare or assign null values to a variable.

                            
let a= null    //
  
                        
    
                    

undefined is a global variable, which contains the value undefined. It is the property of the global object. Hence you can access it using the window object (only in the browser) or using the globalThis property.

                    
console.log(undefined)          //undefined
console.log(typeof(undefined))  //undefined
 
console.log(window.undefined)          //undefined
console.log(typeof(window.undefined))  //undefined
 
console.log(globalThis.undefined)          //undefined
console.log(typeof(globalThis.undefined))  //undefined
    
        
    

Since the ES5 version, the undefined is a non-configurable, non-writable & non-enumerable property. But that does not stop someone from overriding it inside a function.

        
abc()
 
function abc() {
    var undefined=10
    console.log(undefined)      //10
    console.log(typeof(undefined))  //number
}





Undefined vs null. Which one to use

There are many approaches on how to use undefined & null. The simplest approach would be to use the null to indicate the no value. Use undefined to indicate that the variable is not yet assigned any value. In this use case, you should not assign undefined to any variable.

You can also use undefined to indicate the no value and never use null.

Read More

  1. JavaScript Tutorial
  2. Data Types in JavaScript
  3. JavaScript String
  4. Template Strings & String Interpolation
  5. Tagged Templates
  6. String to Number
  7. EPSILON & Floating Point Precision
  8. Infinity
  9. BigInt
  10. BintInt Vs Number