Reputation: 7416
I was wondering if in a weakly typed language such as javascript, is there a significant difference between using
var someBool=true;
if (someBool==true){
//Somecode
}
Or just using
if(someBool){
//Somecode
}
Is there a difference in the speed of execution, or is there some semantic difference, or is one just preferred over the other?
Upvotes: 2
Views: 402
Reputation: 7011
If you want to check that someBool
is in fact true
, use the strict equality comparator (===
):
var someBool = 1;
someBool == true; // true
someBool === true; // false
This also works for other types:
0 == "0"; // true
0 === "0"; // false
As others have pointed out, there is a difference between testing for equality (using ==
) or testing for "truthyness" (using just if()
). It's definitely worth knowing about this, but personally I try to avoid writing code that is not 100% clear in its meaning. Given the name of the variable (someBool
), I would expect a boolean, so I would test for a boolean. If I wanted to know if it was greater than 0
, I would test for that instead (someNumber >== 0
).
As for performance; the strict equality comparator is usually a bit faster than using ==
, but the difference is negligible. Testing for truthyness might be a bit faster, but this is still a micro-optimization, which is rarely worth the trouble.
Upvotes: 1
Reputation: 660004
The semantic differences are considerable, and they are as follows:
if (x)
has the semantics:
x
. if (x==true)
has the semantics:
x
.if (x==1)
and start over.
I'm not going to go through all the logic for determining if an expression is equal to 1; you can read section 11.9.3 of Revision 3 of the ECMAScript specification if you want the details.
Upvotes: 4
Reputation: 664365
Yes, there is a little semantic difference. The ==
comparison does more if you have different types of values (e.g. JavaScript truthiness in boolean to numbers comparison, What Are the Semantics of Javascripts If Statement), while if
only checks for truthiness.
Yet, if someBool
is always known to be a boolean value you should not compare against true
, but always use the second variant.
Upvotes: 2