Search code examples
javascriptis-emptyappconkit

How do i compare against an empty variable?


If I set a variable to 0, I get the weird behavior that a comparison to "" (empty) is true. How do I check that the variable is really empty?

tmp = 0;

if ( tmp != "")
{
    //do something - This is where the code goes.
}
else
{
   //isEmpty - I would expect to be here
}

Solution

  • Use strict comparison operators === and !==

    With == and != (called abstract comparison operators),

    If the two operands are not of the same type, JavaScript attempts to convert the operands to an appropriate type for the comparison.


    If by empty, you want to check if the variable hasn't been defined, use:

    if (typeof tmp !== "undefined") {
        // it exists!
    }