
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between Null and Undefined in JavaScript
In this article, we will learn about the difference between null and undefined in JavaScript. In JavaScript, null and undefined represent the absence of a value, but they have different meanings and use cases.
What is undefined in JavaScript?
It means a variable declared, but no value has been assigned to the variable. JavaScript automatically assigns undefined to uninitialized variables.
For example
Below is an example of undefined in javascript ?
var demo; alert(demo); //shows undefined alert(typeof demo); //shows undefined
Output
undefined undefined
What is null in JavaScript?
null is an intentional absence of a value. It is often used when a developer wants to indicate that a variable or object property has no value. null in JavaScript is an assignment value. You can assign it to a variable.
For example
Below is an example of null in javascript ?
var demo = null; alert(demo); //shows null alert(typeof demo); //shows object
Output
null object
Difference Table
The following are the key differences between null and undefined ?
Feature | null | undefined |
Meaning | Intentional absence of a value | The variable has not been assigned a value |
Type | object (typeof null ? "object") | undefined (typeof undefined ? "undefined") |
Default Value? | No, must be explicitly assigned | Yes, automatically assigned to uninitialized variables |
Usage | Used when we want to explicitly set a "no value" state | Used when a variable is declared but not initialized |
Conclusion
In JavaScript, use null to explicitly indicate that a variable has no value or is intentionally empty. Use undefined when something is naturally missing, such as an uninitialized variable or a non-existing object property. null represents intentional absence, while undefined signals an expected missing value.