Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in Web Technology by (47.6k points)

Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not undefined or null? I've got this code, but I'm not sure if it covers all cases:

function isEmpty(val){ 

return (val === undefined || val == null || val.length <= 0) ? true : false; 


1 Answer

0 votes
by (106k points)

To check for null, undefined, or blank variables in JavaScript you can use typeof method below is the code for that:-:-

if( typeof foo !== 'undefined' ) { 

// foo could get resolved and it's defined


If you can be sure that a variable is declared at least, you should directly check if it has a truth value like shown above.

The above method will cover cases where the value was never defined, and also any of these:

  • null

  • Undefined

  • 0

  • empty string

  • false

  • NaN

Browse Categories