JavaScript

Best way to Check null, undefined, empty variables in JavaScript

Share your learning

How to check for null, undefined, empty variables in JavaScript where the variable could be anything like array or object, string, number, Boolean?

Hi, coder

So, this is one of the most asked questions that how to check null, undefined, empty variables in JavaScript?

Today we will achieve this by using one simple function which we can add into our scripts easily.

Also Read: A simple way to add image or icon in HTML select box with jQuery?

Let’s dive into it,

console.log('is empty : test 1 >> ', isVarEmpty(0));
console.log('is empty : test 2 >> ', isVarEmpty(''));
console.log('is empty : test 3 >> ', isVarEmpty(null));
console.log('is empty : test 4 >> ', isVarEmpty(NaN));
console.log('is empty : test 5 >> ', isVarEmpty(false));
console.log('is empty : test 6 >> ', isVarEmpty());
console.log('is empty : test 7 >> ', isVarEmpty([]));
console.log('is empty : test 8 >> ', isVarEmpty({}));
console.log('is empty : test 9 >> ', isVarEmpty("has value"));

function isVarEmpty(val = undefined) {

  if ( typeof val !== 'undefined' && val ) {
    if ( typeof val !== 'object' && `${val}`.trim() ) {
      return false;
    } else  if (Object.keys(val).length > 0) {
      return false;
    }
  }
  return true;

}

Output will be something like this

That’s it.

This function is tested with 9 different kinds of tests. You can test it as per your requirements.

Note: Please let me know in the comment section below if I missed anything.

Satpal

View Comments

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

1 year ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

1 year ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

1 year ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

1 year ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

1 year ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

1 year ago