Best way to Check null, undefined, empty variables in JavaScript
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.
1 thought on “Best way to Check null, undefined, empty variables in JavaScript”