I want to know what is the difference between null and undefined in typescript. I know in javascript it is possible to use both of them in order to check a variable has no value. But in typescript I want to know the difference exactly and when it is better to use each one of them. Thanks.
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.
Difference Between undefined and nullundefined 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.
Both undefined and null are falsy by default. So == returns true. But when we use the strict equality operator (===) which checks both type and value, since undefined and null are of different types (from the typeof Operator section), the strict equality operator returns false.
Only use null if you explicitly want to denote the value of a variable as having "no value". As @com2gz states: null is used to define something programmatically empty. undefined is meant to say that the reference is not existing. A null value has a defined reference to "nothing".
This post explains the differences very well. They are the same in TypeScript as in JavaScript.
As for what you should use: You may define that on your own. You may use either, just be aware of the differences and it might make sense to be consistent.
The TypeScript coding style guide for the TypeScript source code (not an official "how to use TypeScript" guide" states that you should always use undefined
and not null
: Typescript Project Styleguide.
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