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 in JavaScript

The null in JavaScript is a special value & also a data type. The value null represents the intentional absence of any object value. It is one of JavaScript’s primitive values and is treated as falsy for boolean operations. The value of null is represented in JavaScript using the literal null.

What is Null in JavaScript

The value null represents the intentional absence of any object value. It represents nothing or no value. null means we know that the variable does not have any value.

JavaScript also has an undefined value and it means the value is not assigned or e we do not know its value.

Take an example of the following person function which returns the person object. It has two fields. name & dateOfMarriage. The name is a required field because everyone has one. But the dateOfMarriage is optional because not everyone is married.

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

Now, what value do you store in dateOfMarriage if the person is not married ?. We explicitly set its value to null to indicate there is no value, which implies that the person is not married.

                            
console.log(person("Colin Bower", null))      //Null is set explicitly. Person is not married
//{name: 'Colin Bower', dateOfMarriage: null}
 
 
                            
                        
                            
                        

What if someone invokes the function without providing a name or empty name?. In this case, you should return null indicating that there is no person (or the better option is to throw an error).

                            
function person(name, dateOfMarriage) {
 
    if (name===undefined || name==="") return null
 
    return { 
        name: name, 
        dateOfMarriage: dateOfMarriage, 
    }
}
 
console.log(person())                   //null
console.log(person(""))                 //null
 
 
                            
                        
                            
                        

Assigning Null

JavaScript does not assign null to any variable. But we can do it by assigning literal null to a variable

                            
let a = null     
console.log(a)    // null
 
 
                            
                        
                            
                        

In the above example in line 1 (let a= null), we assign null value to the variable a. Here null is literal and represents the value null.

A literal is a notation for representing a fixed value in the source code. For Example, 1 is literal, because it represents the number 1. “hello” is literal because it represents the string “hello”. Similarly null is literal because it represents the value null.

Checking for null

You can check for null using the strict equality checker and comparing it against the null literal

                            
let a=null
 
 
console.log(a  === null) // => true
 
 
 
                            
                        
                            
                        

Use the strict equality checker because the loose equality checker returns true even when the variable is undefined.

                            
let num;

let a           // a is undefined
 
console.log(a)         //undefined
console.log(a == null) // => true
 
 
                            
                        
                            
                        

null is falsy

IThe null along with false, 0, '', undefined, NaN is considered as falsy values in JavaScript. Whenever JavaScript encounters a null in an expression it implicitly coerces it to false

                            
let a =null
 
if (a) {
    console.log("true")     //this code does not execute
}
 
if (!a) {
    console.log("false")    //false
}
 
 
                            
                        
                            
                        

But that does not mean that null is false. It is neither false nor true. null does not have any value

                             
                            let a =null
 
 //loose equality check
  
 console.log(a==false)       //false
 console.log(a==true)        //false
  
  
 //Strict equality check
  
 console.log(a===false)      //false
 console.log(a===true)       //false
  
 
                            
                        
                            
                        

The undefined in JavaScript is also treated as no value. Hence running a loose equality checker between them will return true

                             
let a
console.log(a==null)     //true because both null & undefined is treated as no value
  
 
                            
                        
                            
                        

That is the reason why you should use the strict equality checker which also checks the data type.

                                                
let a
console.log(a===null)    //false because Becuase types are different
  
 
                            
                        
                            
                        

typeof null is object

Although the data type of null value is null, the TypeOf operator incorrectly returns “object”. This is a very old bug in JavaScript. The bug is not fixed as it will break many existing codes.

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

Null pitfalls

Accessing a null value can result in surprises if you are not careful. The following are some of the

When used in a numeric expression, JavaScript coerces null to 0

                            
console.log(null+10)   //10
console.log(null*10)   // 0
console.log(null+null)  //0
console.log(Number(null)) //0   
  
 
                            
                        
                            
                        

While in a string expression JavaScript coerces it to “null”

    
console.log(null+"10")   //null10

    

    

False if we use it in a boolean expression.

                            
let a =null
 
if (a) {
    console.log("true")     //this code does not execute
}
 
if (!a) {
    console.log("false")    //false

}


    

If we try to access the property of a null, then it will throw theCannot read property ‘value’ of null error.

                            
let a=null
console.log(a.name)  //   Cannot read properties of null (reading 'name')
  

    

You can make use of optional chaining (?) with nullish coalescing (??) to get around it

                            
let a=null
console.log(a?.name ?? "Not found")  //   Not found