What is the difference between null, undefined and undeclared in JavaScript?
The difference between 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
are both primitive data types in JavaScript, just like any other primitive 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 was responded, it will change to the corresponding data type.
In the following example, we have a variable users
, define its type as
UserDTO[] | undefined
instead of
UserDTO[] | null
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
profilePicture: string | null;
instead of
profilePicture: 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
, it is called undeclared. If we try to call this variable, a ReferenceError
error will be reported.
console.log(x); // Uncaught ReferenceError: x is not defined