What’s the difference between an undefined and null value in Javascript. If you are new to Javascript, probably you will find difficulty in understanding the difference between undefined and null value. How to check whether a variable is undefined or null.
Javascript has five primitive data types.
i) String
ii) Number
iii) Boolean
iv) Undefined
v) Null
The last two types undefined and null represents no value. Let’s understand, what’s the difference between undefined and null value.
Difference Between Undefined and Null Value in Javascript
In the case of undefined in Javascript, Either a variable is not declared. Or a variable is declared but no value is assigned to it. When you declare any variable in a javascript, the default value of a variable is undefined. To test this case, open a console and create any variable and press enter. It shows undefined.
As compared to undefined, Null is an assignment value, it can be assigned to a variable in case of no value or empty value.
Let’s understand this concept using an example.
Let’s create one variable in Javascript.
1 2 3 4 5 |
var first; alert(first); // Prints undefined alert(typeof first); // Prints undefined. It means undefined is type as well. |
Now, Let’s initialize null to a variable.
1 2 3 4 5 |
var first = null; alert(first); // Prints null alert(typeof first); // Prints object, null is a type of object. |
We have seen through example that undefined is a type itself whereas null is a special type of object.
For reference –
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/null