Check undefined and empty variable in Javascript

Javascript undefined and empty variable check is a simple yet confusing issue. I have come across this problem couple of times too and finding a proper solution to address it is yet more confusing. Hence, I have summarized it here.

Ocassionally, while referencing an undeclared variable in Javascript, it throws an error.

If we view the Javascript Error Console, we can see the error like 'Variable is not defined'. Once the javascript code encounters such error, the further lines of code cannot be executed. Hence, such errors need to be checked well in advance.

These errors occur when referencing a variable that is not declared. The Javascript interpreter will not find any reference of the variable and assign that variable's type to undefined. Hence, the undeclared variable check can be done with the simple lines of code below.

if(typeof testVar === 'undefined') {
// enters here if the variable is undefined

This condition will return true under two conditions below.
1. testVar is not declared.
2. var testVar = undefined; // testVar is declared and assigned to undefined

An empty variable check can be carried out in the following way.
if(!testVar) {
// enters here

This condition holds true under following conditions for the variable testVar.
1. var testVar; // testVar is declared but not assigned
2. var testVar = ''; // testVar is declared and assigned to empty String
3. var testVar = 0; // testVar is declared and assigned to 0
4. var testVar = false; // testVar is declared and assigned to false
5. var testVar = undefined;// testVar is declared and assigned to undefined
6. var testVar = null; // testVar is declared and assigned to null

NOTE: This condition will throw an error if testVar is undeclared.

Hence, undefined and empty check can be carried out altogether as below:
if(typeof testVar === 'undefined' || !testVar) {
// testVar is undefined or empty

NOTE: In the above condition, undefined check should be done first otherwise it will throw an error as the testVar will not be declared by then.