-5

In JavaScript when verifying true condition

Below

if(variablename=='true') 

is working but

if(variablename==true) 

is not working. Any reasons for this? Is it specific to some browsers?

j08691
  • 204,283
  • 31
  • 260
  • 272

1 Answers1

-1

Strings and booleans aren't the same thing at all. Non-empty strings are all equivalent to true (How can I convert a string to boolean in JavaScript?). You need to determine what the type of variablename is and implement the appropriate comparison.

The difference between 'true' and true is similar to the differences between '3' and 3, or 3.0 and 3. In many cases they will "work". Using these assumptions and implicit coercions is not safe and will eventually cause trouble.

Languages such as JavaScript that support implicit coercions give you plenty of rope. It's up to you to not hang yourself with it.

Community
  • 1
  • 1
Robert Columbia
  • 6,313
  • 15
  • 32
  • 40
  • 2
    How are `3.0` and `3` different? And no, the difference between `'3'` and `3` is **not** similar to the difference between `'true'` and `true`. Nor is it correct to say that "non-empty strings are all equivalent to true". I guess what you meant to say is that "non-empty strings are considered true in a boolean context (in other words, 'truthy')". –  Jun 20 '16 at 16:46
  • I meant that they are different in some languages. – Robert Columbia Jun 22 '16 at 20:44