What is the difference between null and undefined in JavaScript?
Asked on Jul 18, 2024
Answer
In JavaScript, "null" is an intentional absence of any object value, while "undefined" indicates a variable that has been declared but not yet assigned a value.
// Example of undefined
let a;
console.log(a); // Output: undefined
// Example of null
let b = null;
console.log(b); // Output: null
Additional Comment:
✅ Answered with JavaScript best practices.- "undefined" is the default value for variables that are declared but not initialized.
- "null" is an assignment value that represents no value or no object.
- Use "null" when you want to explicitly indicate that a variable should be empty.
- Comparing "null" and "undefined" using "==" results in true, but using "===" results in false because they are of different types.
Recommended Links:
← Back to All Questions