0

If I have a variable x = ""

And I check for the following condition if x != 0

Is it evaluated as false across all the browsers ?

Why is 0 treated the same as "" ?

copenndthagen
  • 49,230
  • 102
  • 290
  • 442

3 Answers3

4

When you use the == operator JavaScript attempts to convert both operands to the same type for comparison. When you have a string and a number it attempts to convert the string to a number. "" converts to 0, giving you this result.

Because of this behaviour many people chose to use the === and !== operators instead. Their operands must be the same type to be considered equal.

Jeremy
  • 1
  • 85
  • 340
  • 366
  • +1 for pointing out that in the case of one string and one number across `=`, JavaScript will convert the string to a number first. However "finding no value" is not the real reason that the empty string is converted to zero. The string `"dog"` is converted to `NaN`, even though you could argue it couldn't "find a value" :-) – Ray Toal Aug 25 '11 at 06:56
  • @Ray, agree, another example, a string consisting only on white-space characters, e.g. `" \t\n\r"` is also converted to `0`, just like the empty string... – Christian C. Salvadó Aug 25 '11 at 07:04
1

Because both 0 and '' are evaluated like this:

0 == false  //true
'' == false //true

Use === to check properly

Thor Jacobsen
  • 8,621
  • 2
  • 27
  • 26
  • 1
    Actually that is not true. `0` does not "evaluate to" false, nor does the empty string "evaluate to" false. What happens when a string and a number are compared with `==`, JavaScript attempts to convert the string to a number and then do a numeric equality comparison. It has nothing at all to do with falsiness in this case. That's probably why `==` gets such a bad rap. No one really understands it. Try `null == 0` for example. They are both falsy, but they are not `==` to each other. – Ray Toal Aug 25 '11 at 06:59
0

Is "" that when casted is egual to 0:

"" != 0 -> string != int -> (int)string != int -> int != int

Fabio Cicerchia
  • 649
  • 3
  • 8
  • 23