We have seen null or nil values in different programming languages. But there is an exception in JavaScript. In JavaScript we can see both undefined and null. The developers try to use them interchangeably, but they are not the same.
In this post, I will help you to understand the difference between undefined and null.
What is undefined in JavaScript ?
A variable in JavaScript contains undefined before a value is assigned to that variable.
Let me elaborate it bit further with a code snippet.
I have declared a variable called name and logged both its value and type to the console. In javaScript you can use typeof operator to check the type of a variable.
You can see both its value and type are undefined. The reason why name is undefined is we only declared the variable, but we did not assign any value.Hence the value is undefined
The type of name is also undefined. The reason for that is in javaScript undefined is a value and also it is a type. It is one of JavaScript’s primitive types.
Now I am going to assign a value to the variable name.
As you can see in the above code snippet, name now holds the value ‘Gihan’ and its type is now string .
We assigned a value to our variable so our variable is no longer undefined.
Did you know that we can label a variable as undefined ?
We can use undefined as an identifier. i. e as a variable name in any scope other than global scope, because undefined is not a reserved word.
I have declared a variable name as undefined in global scope and it throws an error.
I then declare a variable named undefined inside a IIFE function and it works as expected. IIFE functions (Immediately Invoked Function Expressions) are functions which get executed when they are initialised. I will discuss more about IIFE functions in another post. All you should know here variable we have declared inside IIFE function does not belong to global scope.
While it is still possible to declare a variable as undefined in any scope other than global scope, labelling a variable as undefined is NOT recommended at all as it can create lot of confusion
What is null in javaScript ?
null represents intentional absence of any object value. If you want to make a variable empty you can assign null value to it.
null is a primitive value in javaScript and it is considered as falsy in boolean operations.
I have declared a variable called productName and assigned null value to it.
When we log the value of productName, you can see it is null. The typeof our productName is an object.
Why the typeof null is an object ?
Short answer is typeof null is an object since the beginning of javaScript.
Understanding differences between undefined and null
- typeof null is object whereas typeof undefined is undefined
- null == undefined will return true. This is double equal which checks only for value.
- null === undefined will return false. This is strict equality which checks for both value and type