In JavaScript, both null and undefined represent “no value,” but they are used in different scenarios and have subtle differences that are important to understand.
undefined – A Variable That Has Been Declared But Not Assigned
undefined is the default value assigned to:
- Variables that are declared but not initialized
- Function parameters that are not passed
- Missing properties in an object
let x;
console.log(x); // undefined
function greet(name) {
console.log(name);
}
greet(); // undefined
const person = {};
console.log(person.age); // undefined
null – A Value That You Intentionally Set
null is used when you want to intentionally assign “no value” to a variable. It represents the intentional absence of any object value.
let selectedColor = null; // No color selected yet
Type Comparison
Both null and undefined are falsy values in JavaScript:
Boolean(null); // false
Boolean(undefined); // false
But their types are different:
typeof null; // "object" (this is a historical bug in JS)
typeof undefined; // "undefined"
Equality Comparison
null == undefined; // true (loose equality)
null === undefined; // false (strict equality)
When to Use What?
- Use
undefinedwhen a variable hasn’t been initialized. - Use
nullwhen you want to explicitly indicate “no value.”
Conclusion
While both null and undefined represent the absence of a value, undefined means “not assigned yet” while null means “deliberately empty.” Understanding the difference can help you write cleaner, more intentional code in JavaScript.
Post a Comment