In this article we will learn how to check null values using JavaScript.
The null value represents the absence of any object value. It is one of the primitive value in JavaScript and is falsy for boolean operations.
In this article we will check one of the way to determine if a value is null or not.
Create isNull() function in JavaScript
In JavaScript we can create a function call isNull() which will check if a value is null or not.
function isNull(val){
if(val === null){
return true;
}
return false;
}
console.log(isNull(null)) // true
console.log(isNull('')) // false
console.log(isNull(0)) // false
console.log(isNull(undefined)) //false
console.log(isNull(NaN)) //false
Why use === instead of == ?
The ==
(loose equality operator) performs some kinds of coercion. So, when we compare something like this
console.log(' ' == 0) // true
console.log(undefined == null) // true
The == operator says that both the comparison are true
.
Now, if we do the same comparison with === (strict equality operator) we get the results as false
.
console.log(' ' === 0) //false
console.log(undefined === null) //false
Therefore, we have used the === operator to get accurate results.
Using Lodash or Underscore.js _.isNull() Function
We can also use external JavaScript libraries like Lodash or Underscore to check for null values.
The library checks whether the value of the object is null or not. If the value is null it will return as true
otherwise false
.
Syntax:
_.isNull(object)
Example:
console.log(_.isNull(10)) // false
console.log(_.isNull(null)) //true
Related Topics:
How To Write IsNumber() In JavaScript?