Thursday, December 26, 2024
Google search engine
HomeLanguagesJavascriptNull in JavaScript

Null in JavaScript

The null keyword in JavaScript is a falsy data type that denotes that the data type is null. Falsy type refers to the coercion of null to false during conditional statement executions.

Null is an object in JavaScript and represents primitive data types. A null value in JavaScript is used for referring absence of any object value and if any function or variable returns null, then we can infer that the object could not be created. If we pass null as the default parameter to any function type it would take the ‘null’ as a value passed to it.

Syntax:

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

 

Example 1: This example describes the Null value in JavaScript.

Javascript




<script>
    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
</script>


Output:

100
null

Explanation: In this example, 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.

Example 2: Another example that will illustrate Null in JavaScript:

Javascript




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


Output:

var1 is null

Explanation: In this example, we have declared var1 as null. As we know that var1 is a falsy value therefore the else block gets executed only.

RELATED ARTICLES

Most Popular

Recent Comments