5

I see in some javascript codes that people write something like this:

var myVar = "true";

//...

if(myVar == "true") {
     //...
}else{
     //...
}

Why people don't use TRUE or FALSE? As far as I know boolean type is obvious for browsers.

Or is just a poor code ... and try to never write in this way.

Radek
  • 670
  • 7
  • 16

3 Answers3

7

It's just poor code. Try to never write in this way.

This kind of code is just horrible for maintainability. Both the == (instead of ===) and the true as string.

PS: besides, "true" == true // false. For the === argument, it's simply because true == 1 // true, and a lot of others look alike stuff like this.

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
4

You should not do this, unless you really expect a string that contains true for some reason :). But even in that case, using strict equality (===) would be the right choice.

In the code example you are showing, this is simply a terrible way of writing code.

Community
  • 1
  • 1
kapa
  • 77,694
  • 21
  • 158
  • 175
1

It's just poor code, as you say.

A "real" developer never writes if (condition == true), but only if (condition)

Could also be written if (true == condition). This is called Yoda style and is designed to prevent unwanted assignment of variables if you mistakenly write = instead of ==.

Cyrille
  • 25,014
  • 12
  • 67
  • 90