Open In App

Null in JavaScript

In JavaScript, `null` represents the intentional absence of any object value. It is a primitive value that signifies the absence of a value or a placeholder for an object that doesn’t exist. It is distinct from `undefined`, which indicates a variable that has been declared but hasn’t been assigned a value.

Null Syntax:

let number = null;
console.log("Type of number is:" ,typeof number);

Null in JavaScript Example:

This example describes the Null value in JavaScript.






class Square {
    constructor(length) {
        this.length = length;
    }
    get area_of_square() {
        return Math.pow(this.length, 2);
    }
 
    // Static function that returns the length
    static create_function(length) {
        return length > 0 ? new Square(length) : null;
    }
}
 
let variableOne = Square.create_function(10);
console.log(variableOne.area_of_square);
 
let variableTwo = Square.create_function();
console.log(variableTwo); // null

Output:

100
null

Explanation:

Here, there is a Square class that has a constructor that takes length as the argument. The Square class has a static method named create_function() which returns a new Square object that has a specified length. Here, there are two scenarios one in which we pass an argument and another one in which we do not pass an argument.



In the first scenario, we create variableOne that creates a new object of Square, and a value of 10 is passed in the create_function() method. In the second scenario, we have created variableTwo but we do not pass anything there and therefore it returns a null as output.

Null in JavaScript Example:

Another example that will illustrate Null in JavaScript.




const var1 = null;
if (var1) {
    console.log('var1 is not null');
} else {
    console.log('var1 is null');
}

Output:

var1 is null

Explanation:

Here, we have declared var1 as null. As we know that var1 is a falsy value therefore the else block gets executed only.

Use Cases of Null in JavaScript

1. Object Initialization:

If an object couldn’t be created, returning null is a common practice:




class Square {
  constructor(length) {
    this.length = length;
  }
  static createSquare(length) {
    return length > 0 ? new Square(length) : null;
  }
}
 
const square1 = Square.createSquare(10); // Creates a valid Square object
const square2 = Square.createSquare();   // return null
 
console.log(square1);
console.log(square2);

Output:

Square { length: 10 }
null

2. Checking for null:

Use null to indicate that a value is intentionally absent:




const myValue = null;
if (myValue) {
  console.log("Not null"); // This won't execute
} else {
  console.log("Null"); // Output: "Null"
}

Output:

Null

Key Takeaways

Remember, mastering null will enhance your JavaScript skills.


Article Tags :