![]() |
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.
Output: undefined 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.
Output: undefined 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.
Output: 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.
Output: true Method 5: Using Optional Chaining and Nullish Coalescing OperatorIn this approach, we utilize the optional chaining (?.) and nullish coalescing (??) operators to check if a variable is null or undefined. These operators provide a concise and readable way to handle null and undefined values in TypeScript. Example: Below is an example demonstrating the use of optional chaining and nullish coalescing operators to check for null or undefined values. Data: Variable DeclarationWe declare variables that can be either undefined, null, or assigned a value. let undefinedVar: string | undefined;
Output: Variable is undefined |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 8 |