Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 563
Enigma Avatar asked Jul 04 '26 10:07

Enigma


1 Answers

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!
}
like image 158
Anirudh Ramanathan Avatar answered Jul 10 '26 11:07

Anirudh Ramanathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!