Photo by Glenn Carstens-Peters on Unsplash
What is the difference between JavaScript null, undefined and undeclared?
Table of contents
No headings in the article.
The post was originally published on ExplainThis with title 《What is the difference between JavaScript null, undefined and undeclared?》
undefined
means that the value has not yet been defined, so when a variable is declared but not assigned any value, the variable will be undefined
, which can be understood as "not yet".
null
represents the empty value of a variable, which can be understood as "nothing".
undefined
and null
in JavaScript, both belong to one of the primitive data types (primitive data types), just like any other data types (data types), such as: string
, number
, can be assigned to the variable. Both have different meanings in use.
For example, when the front-end wants to request data from the back-end, because it needs to wait for the data to be returned, a certain variable may be undefined
at the beginning, and when the data comes back, it will change to this data type. In the following example, we have a variable users
, define its type as UserDTO[] | undefined
instead of UserDTO[] | null
precisely because before getting the data, users
is "Not yet".
type UserDTO = {
id: string;
firstName: string;
lastName: string;
profilePicture: string | null;
};
const users: UserDTO[] | undefined = await fetchUsers();
Vice versa, in the above example, when users
is obtained, some users do not have a profile picture, because it is "none", so the type of profilePicture
is string | null
instead of string | undefined
.
undeclared
is often compared with undefined
, undefined
means that it has been declared as a defined value, but undeclared
means that it has never been declared. When a variable has not been declared using var
, let
or const
, if we try to call this variable, a ReferenceError
error will be reported.
console.log(x); // Uncaught ReferenceError: x is not defined