3

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
}
Enigma
  • 125
  • 4

4 Answers4

4

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!
}
Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
  • Well I'm not sure whether "undefined" is what I was looking for, but the strict comparison was new to me. Now the code goes where I expected it to go. :) Thanks! – Enigma Apr 17 '13 at 10:01
0

What do you mean by empty variable? If you mean an empty string, then you should use !== to check it.

if (tmp !== "")
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

JavaScript implicitly converts values to other types. To check type also, use the !== operator:

if ( tmp !== "")
PurkkaKoodari
  • 6,703
  • 6
  • 37
  • 58
0

In JavaScript everything except 0, NaN, undefined, false and null are considered to be false. "" is considered as true.

if (tmp) {

}

Above if will be executed if variable contains any value other than 0, NaN, undefined, false and null.

If tmp is a string then you can use the following code:

if (tmp !== "") {

}

=== and !== operators compare without doing type-conversion.

Ali
  • 1,409
  • 13
  • 23