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.
Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…
Let's understand about how to use coding to improve your website's SEO. In today’s computerized…
Let's understand the most important linux commands for web developers. Linux, as an open-source and…
Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…
Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…
Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…
View Comments