Boolean in if statement

Today I received a comment about the code, considering how I check if a variable in a school assignment is true or false.

The code I wrote was something like this:

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

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

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

The remark I received 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 a variable is logical or not, especially since Javascript is an uncaught language.

In the second example, the string will also return "something";

So my question is; Whether directly losing the "=== true" part in the future, or is it good practice to check the type of a variable.

Edit: In my "real" code, the logical expression represents whether the image was deleted or not, so the boolValue values ​​that should ever be should be true or false.

0 and 1, for example, should not be in this variable.

+123
javascript semantics
Mar 13 '13 at 18:50
source share
13 answers

First of all, the facts:

 if (booleanValue) 

Will satisfy the if for any true booleanValue , including true , any non-zero number, any non-empty string value, any reference to an object or array, etc.

On the other hand:

 if (booleanValue === true) 

This will only satisfy the if condition if booleanValue exactly true . No other true meaning will satisfy it.

On the other hand, if you do this:

 if (someVar == true) 

Then, what Javascript will do is coerce true to match someVar , and then compare the two variables. There are many situations where this is most likely not what one might intend. Because of this, in most cases, you need to avoid == , because there is a rather long set of rules on how Javascript will introduce coercion so that two things are of the same type, and if you do not understand all these rules and cannot foresee everything, what JS interprets can occur when using two different types (which most JS developers cannot), you probably want to completely avoid == .

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 a value of 2 you might think that 2 is a true value, so it compares favorably with true , but that's not how the forced type action works. It converts the value of the right hand according to the type of value of the left hand, so it converts true to the number 1 , so it compares 2 == 1 , which is certainly not what you expected.

So, buyer beware. It is probably best to avoid == almost all cases unless you explicitly know the types to be compared and know how all possible type-coercion algorithms work.




So this really depends on the expected booleanValue values ​​and how you want the code to work. If you know in advance that it will ever be true or false , then explicitly comparing it to

 if (booleanValue === true) 

is just extra code and unnecessary and

 if (booleanValue) 

more compact and possibly cleaner / better.

If, on the other hand, you do not know what a booleanValue can be, and you want to check if it is really set to true without any other automatic type conversions, then

 if (booleanValue === true) 

- This is not only a good idea, but also a required one.




For example, if you look at the .on() implementation in jQuery, it has an optional return value. If the callback returns false , then jQuery will automatically stop propagating the event. In this particular case, since jQuery wants ONLY to stop propagating if false was returned, they check the expression for the return value for === false , because they do not want undefined or 0 or "" or anything else that automatically converts the type false to also satisfy the comparison.

For example, here is 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 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; } ... 
+191
Mar 13 '13 at 19:00
source share

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

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

+37
Mar 13 '13 at 18:55
source share

In the usual "if" variable will be forced into the Boolean value and it uses toBoolean for 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 comparing with === has no type coercion, so they should be equal without coercion.

If you say that the object may not even be logical, you may need more than just true / false.

 if(x===true){ ... } else if(x===false){ .... } else { .... } 
+8
Mar 13 '13 at 19:17
source share

It depends on your use. It might also make sense to check the type, but if it's just a flag, it is not.

+5
Mar 13 '13 at 18:51
source share

In general, it’s cleaner and easier to omit === true .

However, in Javascript these expressions are different.

if (booleanValue) will execute if booleanValue is right-handed - nothing but 0 , false , '' , NaN , null and undefined .

if (booleanValue === true) will be executed only if booleanValue exactly true .

+4
Mar 13 '13 at 18:53
source share

Since the checked value is Boolean , it prefers to use it directly for less encoding, and generally it does the same ==true

+3
Mar 13 '13 at 18:54
source share

The identity operator (===) behaves identically to the equality operator (==) , except that type conversion is not performed, and the types must be the same in order to be considered equal.

if (booleanValue) essentially if (booleanValue==true)

+3
Mar 13 '13 at 18:54
source share

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

+2
Mar 13 '13 at 18:53
source share

It depends. If you are worried that your variable might be something that allows TRUE. Then a rigorous check is mandatory. Otherwise, it is up to you. However, I doubt that the syntax whatever == TRUE would never confuse anyone who knew what they were doing.

+1
Mar 13 '13 at 18:54
source share

If a variable can only take logical values, then it is wise to use a shorter syntax.

If you can potentially assign other types, and you need to distinguish true from 1 or "foo" , then you should use === true .

+1
Mar 13 '13 at 18:55
source share

In Javascript, the idea of ​​Boolean is rather ambiguous. Consider this:

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

Therefore, when you use the if statement (or any other control statement), you do not need to use the "boolean" type var. Therefore, in my opinion, the "=== true" part of your statement is not needed if you know that it is logical, but absolutely necessary if your value is an ambiguous "true" var. More about boolean in javscript can be found here .

+1
Mar 13 '13 at 19:01
source share

I think your reasoning sounds. But in practice, I found that the comparison === much more common. I think there are three reasons for this:

  • Usually this does not add the meaning of the expression - which is not the case when the value is known as Boolean.
  • Because JavaScript has a lot of type uncertainty, forced type checking tends to bite you when you get an unexpected value of undefined or null . Often you just want your test to fail in such cases. (Although I try to balance this view with the motto "fail fast").
  • JavaScript programmers like to play quickly and freely with types - especially in boolean expressions - because we can.

Consider the following example:

 var someString = getInput(); var normalized = someString && trim(someString); // trim() removes leading and trailing whitespace if (normalized) { submitInput(normalized); } 

I think such code is not uncommon. It handles cases where getInput() returns undefined , null or an empty string. Because of two Boolean evaluations, submitInput() is only called if this input is a string containing characters without spaces.

JavaScript && returns its first argument if it is false or its second argument if the first argument is true; therefore normalized will be undefined if someString undefined etc. This means that none of the input for the boolean expressions above is actually a boolean.

I know that many programmers, accustomed to strong type checking, are compressed when they see such code. But note that applying strong typing will require explicit checks for null or undefined values, which clutters the code. In JavaScript, which is not needed.

+1
Mar 13 '13 at 19:11
source share

Revision https://www.w3schools.com/js/js_comparisons.asp

Example:

 var p=5; p==5 ? true p=="5" ? true p==="5" ? false 

=== means the same type and same value == exactly the same value

enter image description here

+1
03 Sep '19 at 17:56
source share



All Articles