Null, undefined and empty checks in JavaScript

Whenever you are writing code in Javascript, the Most common point comes where you and your code reviewer comes to a point to write fail-safe code. When we are talking about fail-safety, the prominent use case comes to check null, undefined, and empty text values. It is very important to handle these values in order not to come across a code failure at runtime. If there are use cases where your variables attain null or undefined you will be in a position to understand and handle it.

In JavaScript, the state with no value is represented by null or undefined. It is one of the primitive values. The most common way to handle the null value is to just put the variable in if condition check.

Similar to null, undefined is also treated as falsy. The difference between undefined and null is that undefined is undefined and null is of type object. Above if condition which we have seen for null value remains valid for undefined as well. You can utilize the below code to see how it works.

If you want to check string is not empty then you can use the below code. Here I am using strict inequality(!==) operator to check whether string it is empty or not.

You can use inequality(!=) operator to check if the value is an empty string(“”) or zero(0). This will give some multi-value protection. But this condition will fail to handle null or undefined value.

There is good debate on whether to use strict inequality(!==) operator or inequality(!=) operator. In my opinion, if you understand the implications of expression then you can use both in condition checks.

Here is some way you can check value is not equals to null or undefined or empty. This is a more readable form of earlier expressions.

There is one more way you can use check is !!(Variable Name).

Falsy values in javascript are null, undefined, NaN, 0(Zero), ‘‘’’.

You can use any of the above or more to avoid unexpected values in your JavaScript code. Hope this is useful in your day to day coding. Happy coding!!

Comments

Popular posts from this blog

How to do AJAX using XMLHttpRequest for large data

Caching mechanisms in modern world browser

Polymorphism in Java OOP