Use the qualities of the abstract equality operator to find the undefined or null variable in JavaScript. Therefore we use ==
and only compare to null
.
if (variable == null){
// your code here.
}
Because null == undefined
is true, the above code will catch both null
and undefined
. Which is 100% equivalent to the more explicit but less concise:
if (variable === undefined || variable === null) {
// do something
}
JavaScript if not undefined or null
The standard way to catch null
and undefined
simultaneously is this simple example code. This will only match null or undefined, this won’t match false.
<!DOCTYPE html>
<html>
<body>
<script>
var variable;
if (variable == null){
console.log(variable)
}
variable = null;
if (variable == null){
console.log(variable)
}
</script>
</body>
</html>
Output:
if not undefined or null code
will evaluate to true if the value is not:
- null
- undefined
- NaN
- empty string (“”)
- 0
- false
<script>
var variable = "Hello";
if (typeof variable != 'undefined' && variable) {
console.log(variable)
}
</script>
Output: Hello
Do comment if you have any doubts or suggestions on this JS undefined/null topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version