How many values does javascript have for nothing?

JavaScript has two primitive values that represent "nothing": null and undefined. Both indicate the absence of a meaningful value, but they have distinct purposes and behaviors.

Undefined

A variable is undefined when it has been declared but not assigned a value, or when a function doesn't explicitly return anything. JavaScript automatically assigns undefined in these cases.

Example 1 - Variable Declaration

When a variable is declared but not assigned a value:

var str;
console.log('The value of given variable is:', str);
The value of given variable is: undefined

Example 2 - Checking for Undefined

You can check if a variable is undefined using comparison or the void operator:

var myVar;
if(myVar === void 0) {
   console.log("myVar has the value:", typeof(myVar));
}
myVar has the value: undefined

Example 3 - Function Returns

Functions that don't explicitly return a value return undefined:

let a;
console.log(a);

function b() {}
console.log(b());
undefined
undefined

Null

The null value represents an intentional absence of value. Unlike undefined, null must be explicitly assigned by the programmer. Interestingly, typeof null returns "object" due to a historical JavaScript quirk.

Example 1 - Basic Null Assignment

Explicitly assigning null to a variable:

var a = null;
console.log("The value of given variable is:", a);
console.log("The type of null value is:", typeof null);
The value of given variable is: null
The type of null value is: object

Example 2 - Arithmetic Operations

Both values behave differently in arithmetic operations. null is treated as 0, while undefined results in NaN:

var a;
console.log("The variable is:", a, "Type is:", typeof a);
console.log("Value of undefined when addition is done:", a + 1);

var b = null;
console.log("The variable is:", b, "Type is:", typeof b);
console.log("Value of null when addition is done:", b + 1);
The variable is: undefined Type is: undefined
Value of undefined when addition is done: NaN
The variable is: null Type is: object
Value of null when addition is done: 1

Example 3 - Explicit Null Returns

Functions can explicitly return null to indicate no meaningful value:

let a = null;
function b() {
   return null;
}
console.log(a);
console.log(b());
null
null

Key Differences

Property undefined null
Type undefined object
Assignment Automatic by JavaScript Must be explicit
In arithmetic Results in NaN Treated as 0
Purpose Variable declared but not assigned Intentional absence of value

Conclusion

JavaScript has exactly two values for "nothing": undefined (automatically assigned) and null (explicitly assigned). Understanding their differences helps write more predictable code and handle edge cases properly.

Updated on: 2026-03-15T19:58:42+05:30

768 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements