In this article let’s learn how to check if a variable is null or undefined in TypeScript. A variable is undefined when it’s not assigned any value after being declared. Null refers to a value that is either empty or doesn’t exist. null means no value. To make a variable null we must assign null value to it as by default in typescript unassigned values are termed undefined. We can use typeof or ‘==’ or ‘===’ to check if a variable is null or undefined in typescript.
By using typescript compiler tcs we transpile typescript code to javascript and then run the javascript file.
tcs name_of_the_typescript_file
run the javascript file in the terminal by using:
node name_of_the_js_file
Example 1: In this example, we demonstrate when variables are null and when they are null.
Javascript
let s: string; // Returns undefined console.log(s); let n: number; // Assigned null value n = null ; console.log(n); |
Output:
undefined null
Example 2: In this example, typeof operator returns the type of the variable we want to check. In the below example we check the variable. unassigned variable returns undefined and the value which is assigned null returns object as ‘null’ is also taken as a null object in javascript.
Javascript
let s: string; // Returns undefined console.log( typeof s); let n: number; // Assigned null value n = null ; console.log( typeof n); |
Output:
undefined object
Example 3: In this example, ‘==’ the equals operator helps us check whether the variable is null or undefined but when we check if null == undefined it results ‘true’. it’s also known as equality check.
Javascript
let s: string; let n: number; // Assigned null value n = null ; console.log(n == null ); // Returns true console.log(s == undefined); // Returns true console.log( null == undefined); // Returns true |
Output:
true true true
Example 4: In this example, just as in the previous example instead of ‘==’ , we use ‘===’ to check. this method is called strict equality check. when checked if null=== undefined, it returns false unlike the previous method.
Javascript
let s: string; let n: number; // Assigned null value n = null ; console.log(n === null ); // Returns true console.log(s === undefined); // Returns true console.log( null === undefined); // Returns false |
Output:
true true false