jQuery typeof with OR condition

I'm new in jQuery so I want to check variable $test is undefine/empty so my condition is,

var $test = '';

1. 
if (typeof($test == 'undefined' || $test == '')) {  
   console.log('Variable is empty');  
}
else  
{   console.log('variable is not empty');  
}

2. 
if (typeof($test) == 'undefined' || $test == ' ')) {  
   console.log('Variable is empty');  
}
else  
{  console.log('variable is not empty');  
}

Which condition is valid first one or second one. If the second one then why?

Answers 1

  • Neither example you gave is correct:

    1. Your first example put parentheses around both comparisons and this causes them to be treated as a single argument to typeof.

    2. Your second example used typeof correctly but then compared to a single space (' ') instead of the empty string ('').

    Additionally, you should be using the strict equality operator (===) instead of the loose equality operator (==) for your comparisons.

    Combine the two methods (and note that typeof does not require parentheses):

    var $test = '';
    
    if (typeof $test === 'undefined' || $test === '') {
      console.log('Variable is empty');
    } else {
      console.log('variable is not empty');
    }


Related Articles