scrblnrd3
scrblnrd3

Reputation: 7416

using if(someBoolean) vs if(someBoolean==true) in javascript

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

Answers (3)

Peter-Paul van Gemerden
Peter-Paul van Gemerden

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

Eric Lippert
Eric Lippert

Reputation: 660004

The semantic differences are considerable, and they are as follows:

if (x)

has the semantics:

  • Determine the value of x.
  • If the value is undefined, null, zero, NaN, an empty string or false then the condition is considered to be false, otherwise it is considered to be true.

if (x==true)

has the semantics:

  • Determine the value of x.
  • If the value is true then the condition is true.
  • If the value is false then the condition is false.
  • Otherwise, pretend that the user actually wrote

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

Bergi
Bergi

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

Related Questions