Table of Contents
- Undefined vs Null - The differences
- Why is null an object?
- Other Related Concepts
Here as the variable is declared but not assigned to any value, the variable by default is assigned a value of undefined.
For example, when you do not know the value initially you can assign a null to a variable. Let’s see an example.
Here, in the example above, the variable n is given an initial value of null. Later, in the program, the value of the variable has been calculated from an expression.
Undefined vs null - the differences
1) Data types:The data type of undefined is undefined whereas that of null is object. We can find the datatypes of both undefined and null using the typeof operator. But why is null an object? Check out the reason here
2) In arithmetic operationsWhen used in arithmetic operations, undefined will result in NaN (not a number), whereas null will be converted to 0 behind the screens.
Since t is not assigned a value it is by default given a value of undefined. Hence the simple interest calculation results in NaN.
3) Undefined and null are falsy:When used in conditional logic both undefined and null will return false.
Here the boolean double negation operator aka the bang bang operator is used to check the boolean equivalent of a value.
As you can see here, both, variable t which is undefined and variable a which is see to null, return false and hence do not satisfy either of the if conditions and return the output "both t and a are not defined with a value".
As you can see, when the equality operator is used it compares only the values. Both undefined and null are falsy by default. So == returns true.
But when we use the strict equality operator (===) which checks both type and value, since undefined and null are of different types (from the typeof Operator section), the strict equality operator returns false.
To understand more about the difference between abstract and strict equality operator head over to the tutorial over here.