Since TypeScript is strongly-typed, simply using if () {}
to check for null
and undefined
doesn't sound right.
Does TypeScript have any dedicated function or syntax sugar for this?
Finally, the standard way to check for null and undefined is to compare the variable with null or undefined using the equality operator ( == ). This would work since null == undefined is true in JavaScript. That's all about checking if a variable is null or undefined in JavaScript.
Difference Between undefined and null Though, there is a difference between them: undefined is a variable that refers to something that doesn't exist, and the variable isn't defined to be anything. null is a variable that is defined but is missing a value.
It means null is equal to undefined but not identical. When we define a variable to undefined then we are trying to convey that the variable does not exist . When we define a variable to null then we are trying to convey that the variable is empty.
To check for null or undefined , compare the value to both null and undefined , e.g. if (name === undefined || name === null) {} . If either of the two conditions is met, the variable stores a null or undefined value and the if block will run. Copied!
Using a juggling-check, you can test both null
and undefined
in one hit:
if (x == null) {
If you use a strict-check, it will only be true for values set to null
and won't evaluate as true for undefined variables:
if (x === null) {
You can try this with various values using this 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"
if( value ) { }
will evaluate to true
if value
is not:
null
undefined
NaN
''
0
false
typescript includes javascript rules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With