How to Check null Values in JavaScript? | isNull() JavaScript
Find out how to check if object values is null in JavaScript using isNull() function.
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?
Related Posts
How to write isNumber() in JavaScript?
Tutorial on how to code a isNumber() function to check if a value is a number or not in JavaScript.
Generate Random Number in a specific range in JavaScript
This post is about how to generate random number in a given range in JavaScript.
Fix error:0308010C:digital envelope routines::unsupported
Learn to solve the "Error: error:0308010C:digital envelope routines::unsupported" error in Node.js application (Vue, Angular or react) using the solutions in this article.
Press Shift + Enter for new Line in Textarea
Override default textarea behavior on Enter key press without Shift, prevent new lines, and take custom actions like submitting forms instead. Still allow Shift+Enter newlines.
