# boolean in an if statement

Today I've gotten a remark about code considering the way I check whether a variable is true or false in a school assignment.

The code which I had written was something like this:

``````var booleanValue = true;

function someFunction(){
if(booleanValue === true){
return "something";
}
}
``````

They said it was better/neater to write it like this:

``````var booleanValue = true;

function someFunction(){
if(booleanValue){
return "something";
}
}
``````

The remark which I have gotten about the "=== true" part was that it was not needed and could create confusion.

However my idea is that it is better to check whether the variable is a boolean or not, especially since Javascript is a loosetyped language.

In the second example a string would also return "something";

So my question; Is it neater to loose the "=== true" part in the future, or is it good practise to check the type of the variable as well.

Edit: In my "real" code the boolean represents whether an image has been deleted or not, so the only values boolValue should ever have is true or false.

0 and 1 for example shouldn't be in that variable.

• it is readable and good practice to use === – Piyas De Mar 13 '13 at 18:54
• +1 for `=== true`. Avoids confusion!! – gashu Mar 13 '13 at 18:55
• @gashu Consider ` === true` evaluates to false. – Jlange Mar 13 '13 at 19:04
• @Jlange shouldn't it? Please explain – gashu Mar 13 '13 at 19:11
• What I meant by that, is that if you simply wanted to check for a "truthy" existence, that statement would fail, even though it should evaluate to true (  evaluates to true but not without type conversion). It really depends on what you are trying to accomplish with your statement. Use `=== true` when you need to ensure that that the condition is exactly equal to `true`. – Jlange Mar 13 '13 at 21:11

First off, the facts:

``````if (booleanValue)
``````

Will satisfy the `if` statement for any truthy value of `booleanValue` including `true`, any non-zero number, any non-empty string value, any object or array reference, etc...

On the other hand:

``````if (booleanValue === true)
``````

This will only satisfy the `if` condition if `booleanValue` is exactly equal to `true`. No other truthy value will satisfy it.

On the other hand if you do this:

``````if (someVar == true)
``````

Then, what Javascript will do is type coerce `true` to match the type of `someVar` and then compare the two variables. There are lots of situations where this is likely not what one would intend. Because of this, in most cases you want to avoid `==` because there's a fairly long set of rules on how Javascript will type coerce two things to be the same type and unless you understand all those rules and can anticipate everything that the JS interpreter might do when given two different types (which most JS developers cannot), you probably want to avoid `==` entirely.

As an example of how confusing it can be:

``````var x;

x = 0;
console.log(x == true);   // false, as expected
console.log(x == false);  // true as expected

x = 1;
console.log(x == true);   // true, as expected
console.log(x == false);  // false as expected

x = 2;
console.log(x == true);   // false, ??
console.log(x == false);  // false ``````

For the value `2`, you would think that `2` is a truthy value so it would compare favorably to `true`, but that isn't how the type coercion works. It is converting the right hand value to match the type of the left hand value so its converting `true` to the number `1` so it's comparing `2 == 1` which is certainly not what you likely intended.

So, buyer beware. It's likely best to avoid `==` in nearly all cases unless you explicitly know the types you will be comparing and know how all the possible types coercion algorithms work.

So, it really depends upon the expected values for `booleanValue` and how you want the code to work. If you know in advance that it's only ever going to have a `true` or `false` value, then comparing it explicitly with

``````if (booleanValue === true)
``````

is just extra code and unnecessary and

``````if (booleanValue)
``````

is more compact and arguably cleaner/better.

If, on the other hand, you don't know what `booleanValue` might be and you want to test if it is truly set to `true` with no other automatic type conversions allowed, then

``````if (booleanValue === true)
``````

is not only a good idea, but required.

For example, if you look at the implementation of `.on()` in jQuery, it has an optional return value. If the callback returns `false`, then jQuery will automatically stop propagation of the event. In this specific case, since jQuery wants to ONLY stop propagation if `false` was returned, they check the return value explicity for `=== false` because they don't want `undefined` or `0` or `""` or anything else that will automatically type-convert to false to also satisfy the comparison.

For example, here's the jQuery event handling callback code:

``````ret = ( specialHandle || handleObj.handler ).apply( matched.elem, args );

if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
``````

You can see that jQuery is explicitly looking for `ret === false`.

But, there are also many other places in the jQuery code where a simpler check is appropriate given the desire of the code. For example:

``````// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
...
``````
• I have been thinking about this question for while, but haven't had the chance to find anyone to ask. I'd appreciate if you could take a look. stackoverflow.com/questions/32615466/… – momomo Sep 16 '15 at 17:55
• This answer isnt completly correct. 'x == true' wont be true for non-zero numbers. – Teemoh Jun 25 '17 at 17:00
• @Teemoh - I don't understand your comment. See jsfiddle.net/jfriend00/89h8d8tm. – jfriend00 Jun 25 '17 at 17:10
• I just want to say that 'if (x)' is not the same as 'if(x == true)', like you wrote in the first paragraph of your answer. 'if (x)' will explicitly convert 'x' to its boolean representation. 'if (x == true)' will use the EcmaScript Abstract Compare Algorithm. You wrote that 'if (x == true)' will be true for any non-zero number or non-empty string or any object. This is just wrong. If I run your example with 2 instead of 1 it will not work. – Teemoh Jun 28 '17 at 4:35
• @Teemoh - I see your point. Answer corrected and clarified and I added a section on type coercion with an example that show how it can do unexpected things. – jfriend00 Jun 28 '17 at 15:25

If you write: `if(x === true)` , It will be true for only x = true

If you write: `if(x)` , it will be true for any x that is not: '' (empty string), false, null, undefined, 0, NaN.

• (empty string), false, null, undefined, 0, NaN – Oliboy50 Feb 25 '15 at 14:00
• This is the simplest but complete answer – Samitha Chathuranga Feb 2 '16 at 4:47
• Don't forget `NaN` and `-0`. – haykam Jul 13 '16 at 2:55

In the plain "if" the variable will be coerced to a Boolean and it uses toBoolean on the object:-

``````    Argument Type   Result

Undefined       false
Null            false
Boolean         The result equals the input argument (no conversion).
Number          The result is false if the argument is +0, −0, or NaN;
otherwise the result is true.
String          The result is false if the argument is the empty
String (its length is zero); otherwise the result is true.
Object          true.
``````

But comparison with === does not have any type coercion, so they must be equal without coercion.

If you are saying that the object may not even be a Boolean then you may have to consider more than just true/false.

``````if(x===true){
...
} else if(x===false){
....
} else {
....
}
``````

It depends on your usecase. It may make sense to check the type too, but if it's just a flag, it does not.

• The `===` comparison does not perform type coercion. So the OP's code effectively does test the type of the flag. It only succeeds if the value is a boolean and is true. – Jesse Hallett Mar 13 '13 at 18:54
• Let me rephrase. If you know it's gonna be either true or false, it doesn't matter. – Ven Mar 13 '13 at 18:58

In general, it is cleaner and simpler to omit the `=== true`.

However, in Javascript, those statements are different.

`if (booleanValue)` will execute if `booleanValue` is truthy – anything other than `0`, `false`, `''`, `NaN`, `null`, and `undefined`.

`if (booleanValue === true)` will only execute if `booleanValue` is precisely equal to `true`.

• Which is precisely what I want to be sure of, even when I only want boolValue to be true or false. The variable get set to true/false multiple times in the code. I know that when I write the code, but if I check the code again a year later then its just a big question mark unless I re-read everything right? – DirkZz Mar 13 '13 at 19:09
• @aldanux: Oops; I meant `''`. – SLaks Oct 6 '16 at 14:29

Since the checked value is `Boolean` it's preferred to use it directly for less coding and at all it did same `==true`

The identity `(===)` operator behaves identically to the equality `(==)` operator except no type conversion is done, and the types must be the same to be considered equal.

`if (booleanValue)` is essentially `if (booleanValue==true)`

Since you already initialized clearly as bool, I think `===` operator is not required.

This depends. If you are concerned that your variable could end up as something that resolves to TRUE. Then hard checking is a must. Otherwise it is up to you. However, I doubt that the syntax `whatever == TRUE` would ever confuse anyone who knew what they were doing.

If the variable can only ever take on boolean values, then it's reasonable to use the shorter syntax.

If it can potentially be assigned other types, and you need to distinguish `true` from `1` or `"foo"`, then you must use `=== true`.

I think that your reasoning is sound. But in practice I have found that it is far more common to omit the `===` comparison. I think that there are three reasons for that:

1. It does not usually add to the meaning of the expression - that's in cases where the value is known to be boolean anyway.
2. Because there is a great deal of type-uncertainty in JavaScript, forcing a type check tends to bite you when you get an unexpected `undefined` or `null` value. Often you just want your test to fail in such cases. (Though I try to balance this view with the "fail fast" motto).
3. JavaScript programmers like to play fast-and-loose with types - especially in boolean expressions - because we can.

Consider this example:

``````var someString = getInput();
var normalized = someString && trim(someString);
// trim() removes leading and trailing whitespace

if (normalized) {
submitInput(normalized);
}
``````

I think that this kind of code is not uncommon. It handles cases where `getInput()` returns `undefined`, `null`, or an empty string. Due to the two boolean evaluations `submitInput()` is only called if the given input is a string that contains non-whitespace characters.

In JavaScript `&&` returns its first argument if it is falsy or its second argument if the first argument is truthy; so `normalized` will be `undefined` if `someString` was undefined and so forth. That means that none of the inputs to the boolean expressions above are actually boolean values.

I know that a lot of programmers who are accustomed to strong type-checking cringe when seeing code like this. But note applying strong typing would likely require explicit checks for `null` or `undefined` values, which would clutter up the code. In JavaScript that is not needed.

In Javascript the idea of boolean is fairly ambiguous. Consider this:

`````` var bool = 0
if(bool){..} //evaluates to false

if(//uninitialized var) //evaluates to false
``````

So when you're using an if statement, (or any other control statement), one does not have to use a "boolean" type var. Therefore, in my opinion, the "=== true" part of your statement is unnecessary if you know it is a boolean, but absolutely necessary if your value is an ambiguous "truthy" var. More on booleans in javscript can be found here.

example:

``````var p=5;

p==5 ? true
p=="5" ?  true
p==="5" ? false
``````

=== means same type also same value == just same value
{"ft_lang_label":"__label__en","ft_lang_prob":0.81523913,"math_prob":0.8529392,"size":3696,"snap":"2019-35-2019-39","text_gpt3_token_len":873,"char_repetition_ratio":0.11484291,"word_repetition_ratio":0.02431611,"special_character_ratio":0.25351733,"punctuation_ratio":0.13416322,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9528384,"pos_list":[0,1,2],"im_url_duplicate_count":[null,3,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-09-19T12:05:40Z\",\"WARC-Record-ID\":\"<urn:uuid:743424dc-58e9-41d5-b1ed-1bcef1ee6884>\",\"Content-Length\":\"236168\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:9c810345-80b1-4457-ae89-eece16e647aa>\",\"WARC-Concurrent-To\":\"<urn:uuid:671c0abd-cd19-4761-81b1-f540fe5505f3>\",\"WARC-IP-Address\":\"151.101.193.69\",\"WARC-Target-URI\":\"https://stackoverflow.com/questions/15393935/boolean-in-an-if-statement\",\"WARC-Payload-Digest\":\"sha1:O3IPAML6QWXUMW7TIMIFBSHKDEOB6LMQ\",\"WARC-Block-Digest\":\"sha1:WAYIZ55Z3LSTJBDZ4ZS5WZMCLWPDLFMW\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-39/CC-MAIN-2019-39_segments_1568514573476.67_warc_CC-MAIN-20190919101533-20190919123533-00181.warc.gz\"}"}