In many cases, using:
if (elem) { // or !elem
will do the job for you!... this will check these below cases:
- undefined: if the value is not defined and it's
undefined
- null: if it's null, for example, if a DOM element not exists...
- empty string:
''
- 0: number zero
- NaN: not a number
- false
So it will cover off kind of all cases, but there are always weird cases which we'd like to cover as well, for example, a string with spaces, like this ' ' one, this will be defined in javascript as it has spaces inside string... for example in this case you add one more check using trim(), like:
if(elem) {
if(typeof elem === 'string' && elem.trim()) {
///
Also, these checks are for values only, as objects and arrays work differently in Javascript, empty array [] and empty object {} are always true.
I create the image below to show a quick brief of the answer:
