JavaScript/ Typescript object null check?


In this article we will check if an object is a null in Typescript.

A variable is undefined until and unless it is not assigned to any value after declaring it. NULL is known as empty or dosen’t exist. In typescript, unassigned values are by default undefined, so in order to make a variable null, we must assign it a null value.

To check a variable is null or not in typescript we can use typeof or "===" operator.

Using typeofoperator

The typeof operator in JavaScript is used to find the datatype of the variable.

Example

In the example below, we’ve checked the datatype of the variable. We’ve assigned NULL to the object.

let x = null;
console.log(typeof x);

We need to run the above code in node.js terminal to get the output.

Example

In this example below we’ve assigned null to the variable.

let x = null;
console.log(x);

We need to run the above code in node.js terminal to get the output.

Using Strict operator (= = =)operator

The strict equality (===) operator will check whether two operands are equal or not. It will return the result in Boolean value.

Example

In this example below, we’ve assigned NULL to the variable and checked whether object is NULL or not with strict equality operator (===).

let x = null;
console.log(x === null);

We need to run the above code in node.js terminal to get the output.

Example

var value=null;
if(!value) {
   console.log("This is null.");
} else {
   console.log("This is not null.");
}

We need to run the above code in node.js terminal to get the output.


Advertisements