In JavaScript, null
and undefined
both mean "no value", but their semantics and usage are somewhat different.
null
Indicates a null object pointer, used to indicate that a variable has no value. Typically used to indicate the absence of an object, or to reset the value of an object variable.
In actual use, null is usually used in the following scenarios:
- When we need to explicitly set a variable to have no value, we can set it to null.
- When comparing conditional statements, we can compare a variable with null to see if it has a value.
- In a function call, null can indicate that the function has no return value.
It should be noted that in JavaScript, typeof null returns "object", which is a legacy problem.
undefined
Represents an undefined value, used to indicate that a variable has not been initialized, or a property does not exist on the object. In a function, if no return value is specified, it returns by default undefined
.
It should be noted that when comparing whether a variable is undefined, it is better to use the typeof operator, because in some cases, the variable may be overwritten with the undefined value.
In actual use, undefined is usually used in the following scenarios:
- JavaScript returns undefined when we access an undefined variable or property.
- If the function does not explicitly return a value, the function returns undefined by default.
- You can set a variable to undefined to clear its value.
let a = null;
let b;
console.log(a); // 输出 null
console.log(b); // 输出 undefined
In code, when it is necessary to indicate that a variable has no value, it should be used in preference null
instead of undefined
. In some cases, null
and undefined
are used interchangeably, but you need to be aware of the distinction to avoid errors in your code.