Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - What is the difference between null and undefined? [duplicate]

Tags:

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.

like image 478
neomib Avatar asked Jun 14 '17 05:06

neomib


People also ask

What is the difference between null and 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.

What is the difference between null and 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.

Why undefined === null is false?

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.

Is it better to use undefined or null?

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".


1 Answers

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.

like image 163
Spitzbueb Avatar answered Oct 11 '22 09:10

Spitzbueb