Skip to main content

Command Palette

Search for a command to run...

What is the difference between JavaScript null, undefined and undeclared?

Updated
•2 min read•View as Markdown
What is the difference between JavaScript null, undefined and undeclared?
A

A frontend engineering working in a big tech company. In my free time, I write frontend contents and build explainthis.io with my friends 🙂

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

More from this blog

E

ExplainThis

5 posts

ExplainThis curated most common frontend engineering interview questions and solutions. Our goal is to help you land a frontend engineer job the fastest way!