Let’s first discuss JavaScript null vs undefined basic, then we will do an example code.
in JavaScript null means the intentional absence of the value. It is one of the primitive values of JavaScript. And Undefined means value does not exist in the compiler. It is a global object.
undefined
means a variable has been declared but has not yet been assigned a value, such as:
var testVar;
alert(testVar); //shows undefined
alert(typeof testVar); //shows undefined
null
is an assignment value. It can be assigned to a variable as a representation of no value:
var testVar = null;
alert(testVar); //shows null
alert(typeof testVar); //shows object
From the preceding examples, it is clear that undefined
and null
are two distinct types: undefined
is a type itself (undefined) while null
is an object.
null === undefined // false
null == undefined // true
null === null // true
and
null = 'value' // ReferenceError
undefined = 'value' // 'value'
Source: stackoverflow.com
JavaScript null vs undefined example
Simple example code check for an undefined or null variable in JavaScript.
The null
with ==
checks for both null
and undefined
values. This is because null == undefined
evaluates to true.
The following code:
if(variable == null) { ... }
is equivalent to
if (variable === undefined || variable === null) { ... }
Complete code
<!DOCTYPE html>
<html>
<body>
<script>
function checkVariable(variable) {
if(variable == null) {
console.log('The variable is undefined or null');
}
else {
console.log('The variable is neither undefined nor null');
}
}
let newVariable;
checkVariable(100);
checkVariable('hello');
checkVariable(null);
checkVariable(newVariable);
</script>
</body>
</html>
Output:
What is the difference between Null, NaN, and undefined in JavaScript?
Answer:
NaN: Not a number
: As the name implies, it is used to denote that the value of an object is not a number. There are many ways that you can generate this error, one being invalid math operations such as 0/0 or sqrt(-1)
undefined
: It means that the object doesn’t have any value, therefore undefined. This occurs when you create a variable and don’t assign a value to it.
null
: It means that the object is empty and isn’t pointing to any memory address.
Do comment if you have any doubts or suggestions on this JS basic topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version