When writing my previous article nullish coalescing operator, i learned about the differences between null and undefined. Before that i thought both are more or less same but after getting to know about falsy values in javascript. Now i know the difference between them.
Null:
In English the literal meaning of null is having no value. null indicates the intentional absence of value in programming. null is manually assigned by programmers to variable which is declared, initialized and currently hold no value in Javascript. But a value can be expected in future. When we assign null to a variable it is empty or blank. null is of object data type in javascript. An object can be emptied by assigning it to null.
Syntax:
var a = null;
Here we have assigned value null to variable a.
undefined:
undefined means ‘not defined’. Here we declare a variable and does not assign a value to it. The value of undefined variable is set by javascript as undefined.
Syntax:
var a;
Here a variable is created at runtime and if we haven’t passed an argument for a function parameter default value is undefined. When a function doesn’t return a value it is undefined.
Similarites:
- null and undefined denote the absence of value
- Both are primitive Javascript types
- They are falsy values
- undefined and null are loosely equal (==)
null vs undefined:
Using typeof:
When we use typeof it returns object as type for null and undefined as type for undefined variable
var a = null;
console.log(typeof(a));
var b;
console.log(typeof(b));
Output:
object
undefined
Using primitive operations:
In primitive operations null is converted to 0 and undefined to NaN.
var a = 10;
var b;
var c = a+b;
console.log(c);
Output:
NaN
var a = 10;
var b = null;
var c = a+b;
console.log(c);
Output:
10
null | undefined |
It is an assigned value | It is not an assigned value |
It represents an empty or unknown value | Here variable is declared but not assigned any value |
It is a primitive type object in javascript | It is a ES1 feature and is a primitive type by itself |
null indicates absence of value for a variable | undefined indicates absence of variable itself |
Using typeof returns object | Using typeof returns undefined |
By primitive operations null is converted to zero (0) | By primitive operations undefined is converted to NaN |