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. 

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-02-19T17:51:05+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements