How to Accurately Detect Null vs Undefined in JavaScript
In JavaScript, null
and undefined
both represent the absence of a value, but they serve different purposes and have distinct behaviors.
1. Definition
Undefined (undefined
):
undefined
is a primitive type that signifies a variable has been declared but not assigned a value.- If you access an object property that does not exist, it returns
undefined
. - Functions that do not return a value explicitly return
undefined
.
Null (null
):
null
is an object that explicitly represents the absence of a value.- It is often used to intentionally clear a variable or indicate that a property has no value.
2. Type Differences
typeof undefined
returns'undefined'
.typeof null
returns'object'
(this is a historical bug in JavaScript, but it remains for compatibility reasons).
3. Usage Scenarios
When to Use undefined
Declaring a variable without assigning a value:
1 let a;2 console.log(a); // Output: undefined
Accessing a non-existent object property:
1 const obj = {};2 console.log(obj.property); // Output: undefined
Default return value of functions:
1 function test() {}2 console.log(test()); // Output: undefined
When to Use null
Explicitly setting a variable to indicate it has no value:
1 let b = null;2 console.log(b); // Output: null
Representing missing or unknown data in objects:
1 const user = {2 name: "Alice",3 age: null, // Age might be unknown4 };
Initializing variables for future object assignments:
1 let element = null; // Will later be assigned a DOM element
4. Key Differences
Feature | undefined | null |
---|---|---|
Type | undefined | object |
Default Value | Yes, when a variable is declared but unassigned | No, must be explicitly assigned |
Boolean Conversion | false | false |
Usage | Indicates uninitialized state | Explicitly assigned to indicate no value |
5. Additional Code Examples
Checking for Undefined or Null
1 let value;2 if (value === undefined) {3 console.log("Value is undefined");4 }56 let data = null;7 if (data === null) {8 console.log("Data is null");9 }
Handling null
and undefined
Safely
1 function getValue(input) {2 return input ?? "Default Value";3 }45 console.log(getValue(undefined)); // Output: Default Value6 console.log(getValue(null)); // Output: Default Value7 console.log(getValue("Hello")); // Output: Hello
Conclusion
Both null
and undefined
indicate an absence of value in JavaScript, but undefined
is typically used by the JavaScript engine for uninitialized variables and missing properties, while null
is used intentionally by developers to represent an empty or non-existent value. Understanding their distinctions helps prevent bugs and improves code readability.