It is a decision of each language to determine which values are considered true or false and the programmer’s obligation of each of them to know what is the standard adopted by the language you are using.
The most common is that languages decide that false are the "neutral" values, such as zero, and true is any value other than neutral.
It should be noted that some languages give numerical values to true
(1) and to false
(0), but this is not the case for JS.
On the other hand, there are languages that cannot even be compared because the data types are different. Truly strong typing languages do not have this problem, false
is false
and true
is true
, there is no confusion. In weak typing languages it is possible to make some types if they are false or true.
Javascript is like that. But let’s remember that it is also a language that tries to make automatic conversions. And the conversion of true
is made for 1. As well as the conversion of false
is made for 0.
So in this case, the comparison is made to the numerical value and obviously 2 is different from 1. If true
vale 1
the comparison would look like this:
2 == 1
Remembering that the ideal is always to make the comparison used the operator ===
, so the type is taken into account and avoids this kind of problem. In this case the comparison of different types will always be considered false
. The operator ==
It should just be used to do funny things. Even if you really don’t want to take into account the type, you should make the type conversion explicitly, even if the language would do the desired automatically. Being explicit is always more interesting in cases like this.
The ideal is neither to have weak typing, but even if it has only a type coercion precedence in each context for what the programmer expects would already make the language much better.
Banac questions about js :), Operator == and === in Javascript and Why (!+[]+[]+![]). length returns 9 in Javascript?
– rray