How to check for null and undefined values in JavaScript

While working with various data in our application, it is quite often to find some data coming as null or undefined. This shows the absence of that particular data. This might cause some problem to our application. If we are trying to perform some kind of operation on the data which are either null or undefined, then this would break the application. So it would better to do some checks on the data whether they are null or undefined before performing some operation on them.

Basically null shows the absence of any object value, whereas undefined shows the absence of data in some variable. Like if you declared a variable and don’t assign it with some value, then this becomes undefined.

Why do we need to do null checks?

Suppose you are trying to access a DOM element and want to perform some operation on it. But due to server issue the DOM has not loaded yet and the element has not created yet. At that time it will return you null value for that element and if you are performing some operation on null value then it will through you error. Same happens with undefined values. If any variable is undefined and you are trying to perform some operation on it, then it will through error.

That’s why we need to put null and undefined checks before accessing some data which might come as undefined or null. So how do we do null checks then? Let’s discuss in brief.

<div id="content"> This is some content </div>
const element = document.getElementById('content');
if(element !== null) {
   element.innerHTML = "<p> Updated content </p>";
}

To check if any data is undefined, we can check the type of the data using typeof operator or we can simply compare the data with undefined.

let data;
console.log(typeof data === 'undefined'); // true
console.log(data === undefined); // true

For undefined check:

let data;
if (typeof data !== 'undefined') {
    data++;
}

Null and undefined both are falsy values. That means if you put them inside if block then they will act as false. So you can simply put the data inside if block to do null check

const element = document.getElementById('content');
if(element) {
    element.innerHTML = "<p>Updated content</p>";
}

So overall if you feel insecure about the data, then you can put all the null and undefined checks all together before performing operation.

Hope you got a better clarity about null and undefined checks in JavaScript. So start catching those null and undefined values in your code.

References

Leave a Reply

Your email address will not be published. Required fields are marked *