Google News
logo
TypeScript - Interview Questions
How to check null and undefined in TypeScript?
By using a juggling-check, we can check both null and undefined :
if (x == null) {  
} ​
 If we use a strict-check, it will always true for values set to null and won't evaluate as true for undefined variables.
 
Example :
var a: number;  
var b: number = null;  
function check(x, name) {  
    if (x == null) {  
        console.log(name + ' == null');  
    }  
    if (x === null) {  
        console.log(name + ' === null');  
    }  
    if (typeof x === 'undefined') {  
        console.log(name + ' is undefined');  
    }  
}  
check(a, 'a');  
check(b, 'b');​
Output :
"a == null"  
"a is undefined"  
"b == null"  
"b === null"  
Advertisement