Null vs Undefined
In JavaScript, null and undefined both represent the absence of a value, but they are used in slightly different contexts and convey different meanings.
1. Undefined
undefined means a variable has been declared but has not yet been assigned a value. It is the default value of uninitialized variables, function arguments that were not provided, and missing properties of objects.
- Type:
undefined - Meaning: "Value is not assigned yet" or "Value does not exist".
- Origin: Usually set by the JavaScript engine automatically.
let x;
console.log(x); // undefined
function foo(arg) {
console.log(arg);
}
foo(); // undefined
const obj = {};
console.log(obj.prop); // undefined
2. Null
null is an assignment value. It can be assigned to a variable as a representation of no value.
- Type:
object(This is a well-known bug in JavaScript). - Meaning: "Intentionally empty" or "No object".
- Origin: Usually set by the programmer explicitly.
let y = null;
console.log(y); // null
3. Key Differences
| Feature | undefined |
null |
|---|---|---|
| Definition | Variable declared but not assigned. | Assignment value representing "no value". |
Type (typeof) |
"undefined" |
"object" |
| Arithmetic | 1 + undefined = NaN |
1 + null = 1 (converts to 0) |
| JSON | Omitted from JSON strings. | Preserved as null. |
4. Equality Checks
- Loose Equality (
==): They are equal. - Strict Equality (
===): They are NOT equal.
console.log(null == undefined); // true
console.log(null === undefined); // false
5. Best Practices
- Let JS handle
undefined: Don't explicitly assignundefinedto a variable. If you want to clear a variable, usenull. - Check for both: If you want to check if a variable has any value, use loose equality against
null(which catches both).
if (value == null) {
// value is either null or undefined
}
programming/javascript/vanilla/javascript programming/javascript/vanilla/data-types