Questions
What is the difference between `null` and `undefined` in JavaScript?
The Scenario
You are a frontend engineer at a social media company. You are debugging a piece of code and you see that a variable has the value undefined. You are not sure what this means or how it is different from null.
The Challenge
Explain the difference between null and undefined in JavaScript. What are the key similarities and differences between them, and when would you use one over the other?
A junior engineer might think that they are the same thing. They might not be aware of the difference in their meaning or how they are used in different contexts.
A senior engineer would be able to provide a detailed explanation of the differences between `null` and `undefined`. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in a given situation.
Step 1: Understand the Key Differences
| Feature | null | undefined |
|---|---|---|
| Meaning | The intentional absence of any object value. | A variable that has been declared but has not yet been assigned a value. |
typeof | object (this is a bug in JavaScript). | undefined. |
| Usage | Used to indicate that a variable has no value. | Used by the JavaScript engine to indicate that a variable has not been initialized. |
Step 2: Choose the Right Tool for the Job
In modern JavaScript, you should almost always use null to indicate that a variable has no value. You should almost never use undefined.
The only time you would use undefined is when you are checking if a variable has been initialized.
Step 3: Code Examples
Here are some code examples that show the difference between the two approaches:
null:
let myVar = null;
if (myVar === null) {
// ...
}undefined:
let myVar;
if (myVar === undefined) {
// ...
} Practice Question
What will `null == undefined` return?