3 min read
•Question 23 of 50easyWhat is the difference between null and undefined?
Understanding null and undefined values.
What You'll Learn
- Difference between null and undefined
- When each is used
- Checking for both
Comparison
| Aspect | undefined | null |
|---|---|---|
| Type | undefined | object |
| Meaning | Not assigned | Intentionally empty |
| Default | Variable declaration | Must be assigned |
Examples
code.jsJavaScript
// undefined - automatically assigned
let x;
console.log(x); // undefined
function test(a) {
console.log(a); // undefined if not passed
}
const obj = {};
console.log(obj.prop); // undefined
// null - intentionally assigned
let y = null;
function findUser(id) {
// Return null if not found
return users.find(u => u.id === id) || null;
}Type Checking
code.jsJavaScript
typeof undefined // 'undefined'
typeof null // 'object' (historical bug)
// Equality
null == undefined // true
null === undefined // false
// Check for both
if (value == null) {
// Catches both null and undefined
}
// Modern approach
value ?? 'default' // Nullish coalescingNullish Coalescing (??)
code.jsJavaScript
const a = null ?? 'default'; // 'default'
const b = undefined ?? 'default'; // 'default'
const c = 0 ?? 'default'; // 0
const d = '' ?? 'default'; // ''