Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))
In many cases, using:
if (elem) { // or !elem
will do the job for you!... this will check these below cases:
undefined
''
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: