How to Check null Values in JavaScript? | isNull() JavaScript

featured Image

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?

Check If String Is A Number Or Not In JavaScript

How Can I Do String Interpolation In JavaScript?

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more