Typescript - What is the difference between null and undefined?

39,554

Solution 1

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.

Solution 2

The value 'undefined' denotes that a variable has been declared, but hasn't been assigned any value. So, the value of the variable is 'undefined'.

On the other hand, 'null' refers to a non-existent object, which basically means 'empty' or 'nothing'.

You can manually assign the value 'undefined' to a variable, but that isn't recommended. So, 'null' is assigned to a variable to specify that the variable doesn't contain any value or is empty. But 'undefined' is used to check whether the variable has been assigned any value after declaration.

Share:
39,554
neomib
Author by

neomib

Frontend Developer at Priority Software. Love coding and designing. A big fan of Ionic, Angular, and React. In my free time, I paint and write 😀

Updated on October 23, 2020

Comments

  • neomib
    neomib over 3 years

    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.