- Use
nullwhen you want to intentionally indicate the absence of a value or clear the value of a variable. For example, setting a variable tonullsignifies that it explicitly has no value. - Use
undefinedwhen you leave a variable uninitialized or as a default state for missing function returns. It indicates unintentional or default absence.
Null versus undefined in JavaScript
JavaScript has two distinct values for representing the absence of something: null and undefined. While they might seem similar, they serve different purposes and are used in different scenarios. Consider two boxes: one is empty (null), meaning someone intentionally removed its contents, and the other hasn’t been opened yet (undefined), meaning it’s still in its original, untouched state. Understanding the distinction can help you write cleaner and more predictable JavaScript code.
Let’s break down the concepts of null and undefined with examples:
What is undefined?
In JavaScript, a variable is undefined when it has been declared but has not been assigned any value. It is also the default return value for functions that don’t explicitly return anything.
Syntax and example of undefined
let x; // Declared but not initializedconsole.log(x); // Output: undefinedfunction greet() {console.log("Hello!");}let result = greet(); // No return valueconsole.log(result); // Output: undefined
Code explanation:
Lines 1–2: The variable
xis declared but has no value, so it isundefined.Lines 4–8: The
greetfunction returns nothing, so its result isundefined.
Try assigning a value to x and observe how the output changes.
While undefined is a default state, null is a deliberate assignment to represent emptiness. Let’s explore null in detail.
What is null?
null is an object that represents an intentional absence of value. It is explicitly assigned to variables to indicate that they are empty or have no value. null is considered an object due to a historical bug in JavaScript’s implementation. This behavior persists for backward compatibility.
Syntax and example of null
let y = null; // Explicitly assignedconsole.log(y); // Output: nulllet obj = {name: "Alice",age: null, // Indicates no age provided};console.log(obj.age); // Output: null
Code explanation:
Lines 1–2: The variable
yis explicitly set tonull, showing intentional emptiness.Lines 4–8: The
ageproperty in the object isnull, meaning no value is provided.
Difference between undefined and null
Aspect |
|
|
Definition | Indicates a variable is declared but not assigned a value. | Represents an intentional absence of value. |
Type |
|
|
Assignment | JavaScript assigns |
|
Usage | Used for uninitialized variables or missing function returns. | Used to deliberately clear or empty a value. |
Equality Check |
|
|
The following code checks for the absence of user data but does not handle the cases properly. Which option will modify the code to explicitly handle null and undefined values to improve readability?
let user; // Fix this code to handle both null and undefined cases
if (user == null) {
console.log("No user data available.");
}
if (user === null || user === undefined) { console.log("No user data available."); }
if (!user) { console.log("No user data available."); }
Do you know about null == undefined?
In JavaScript, when comparing null and undefined using the == operator, type coercion occurs. This means JavaScript treats these two distinct values as equivalent as they both represent the absence of a value. However, they are not the same type (null is an object, and undefined is a primitive), which is why null === undefined evaluates to false.
Key takeaways
undefinedis automatically assigned to variables that are declared but not initialized or when functions have no return statement.nullis explicitly used to represent intentional emptiness.They are
(loosely equal A comparison (==) in JavaScript that checks for equality after performing type coercion. ==) but is different (strict equal A comparison (===) in JavaScript that checks for equality without performing type coercion, ensuring both value and type match. ===).Use
undefinedfor unintentional absence andnullfor intentional absence.Use
nullto signal intent, such as resetting a variable.Avoid relying on loose equality (
==) to compare null and undefined for clarity.
Ready to learn JavaScript and build interactive web applications? Start our Learn JavaScript course and gain a solid foundation, preparing you for a career in web development.
Want to become a web developer? Begin our Become a Web Developer skill path, starting with the basics and advancing to expert-level skills, setting you up for success in the world of web development.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
When to use null vs. undefined in JavaScript
Is null === undefined true?
Is it better to return null or undefined in JavaScript?
Why is null == undefined true in JavaScript?
Free Resources
- undefined by undefined