0

If I am testing a boolean by itself I know I don't have to put == true.

 if (bool) {
   foo();
 }

I have an if condition that tests for the truthfulness of both a sting's value and a boolean, can I replace:

 if ( string === "hello" && bool == true ) {
   foo();
 }

with:

 if ( string === "hello" && bool ) { 
 foo();
 }

?

Also, would a bool value ever use a triple equal sign? So far what I've seen on bool tests are double equals only.

Thanks.

Justin
  • 569
  • 2
  • 5
  • 8

3 Answers3

3

Use the triple equal sign, it's preferred.

if(bool == true) , if(bool === true) and if(bool) are all different expressions. The first is saying that the value bool must be of the primitive JavaScript type true, or the object representation of the Boolean (i.e. new Boolean()) object with a value of true. The second is saying that the value "bool" must be of the primitive type bool (the new Boolean() object, even with a value of true, will fail). The third expression is only false if bool is

  • false
  • null
  • undefined
  • empty string ''
  • The number 0
  • The number NaN

Meaning, the second expression will evalauate to true if you pass in an empty object ({}), for example.

Some Examples:

var bool = true;
var boolObj = new Boolean(true);
var boolEmptyObj = {};

if (bool === true) { alert("This will alert"); }
if (boolObj === true) { alert("Nope, this wont alert"); }
if (boolEmptyObj) { alert("This will alert"); }
Community
  • 1
  • 1
contactmatt
  • 18,116
  • 40
  • 128
  • 186
1

Yes. If bool is truly a boolean, it will evaluate to true or false, just the same as any expression would. You can also make sure that bool is boolean by using:

!!bool
MattDiamant
  • 8,561
  • 4
  • 37
  • 46
0

Yes, but when you use only bool the value is false for these values: null, undefined, 0 and "" (empty string). You need to be careful.