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;
}
...
Answer from jfriend00 on Stack OverflowFirst 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;
}
...
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.
How do boolean values work with conditional statements?
Should I say boolean === true/false in an if statement?
Depends on the context.
Generally, using truthiness (like in the second block) is idiomatic. You don't need to be defensive about undefined variables if you never expect to work with them.
But, if the null/undefined/etc. case is expected and should be handled differently, then the first block is the idiomatic way of checking for exactly false. These cases are rare, however, and a code block where a certain variable might or might not be defined smells bad.
If you're worried about a case where undefined might arise accidentally (e.g., spelling a variable name incorrectly), consider using a tool like JSHint, which will reliably catch such cases without requiring you to change your style.
More on reddit.comjavascript - How to check if type is Boolean - Stack Overflow
Javascript check if string if true or false and convert to Boolean - Stack Overflow
I've started doing this for boolean variables:
if (booleanVariable === false) { //intent: if boolean variable exists and is false
}(I think) This proves to me that booleanVariable is defined and is false. But coming from Java, it's a little weird to write code this way. Normally you'd say
if (!booleanVariable)
What's the idiomatic way to write the first block?
Depends on the context.
Generally, using truthiness (like in the second block) is idiomatic. You don't need to be defensive about undefined variables if you never expect to work with them.
But, if the null/undefined/etc. case is expected and should be handled differently, then the first block is the idiomatic way of checking for exactly false. These cases are rare, however, and a code block where a certain variable might or might not be defined smells bad.
If you're worried about a case where undefined might arise accidentally (e.g., spelling a variable name incorrectly), consider using a tool like JSHint, which will reliably catch such cases without requiring you to change your style.
The 2nd option is fine - as long as you're okay with it executing whenever booleanVariable is falsy:
-
the boolean false
-
the number 0
-
an empty string
-
null
-
undefined
-
NaN
If you just want to know when the variable is a false boolean - and not any of the above possibilities - then the 1st option is perfect.
That's what typeof is there for. The parentheses are optional since it is an operator.
if (typeof variable == "boolean") {
// variable is a boolean
}
With pure JavaScript, you can simply use typeof and do something like typeof false or typeof true and it will return "boolean"...
But wait, that's not the only way to do that, I'm creating functions below to show different ways you can check for Boolean in JavaScript, also different ways you can do it in some new frameworks, let's start with this one:
function isBoolean(val) {
return val === false || val === true;
}
Or one-line ES6 way ...
const isBoolean = val => 'boolean' === typeof val;
and call it like!
isBoolean(false); //return true
Also in Underscore source code they check it like this(with the _. at the start of the function name):
isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};
Also in jQuery you can check it like this:
jQuery.type(true); //return "boolean"
In React, if using propTypes, you can check a value to be boolean like this:
MyComponent.propTypes = {
children: PropTypes.bool.isRequired
};
If using TypeScript, you can use type boolean also:
let isDone: boolean = false;
Also another way to do it, is like converting the value to boolean and see if it's exactly the same still, something like:
const isBoolean = val => !!val === val;
or like:
const isBoolean = val => Boolean(val) === val;
and call it!
isBoolean(false); //return true
It's not recommended using any framework for this as it's really a simple check in JavaScript.
Most readable:
var thisval = $(this).val();
ao[id] = thisval === 'true' ? true :
thisval === 'false' ? false :
thisval;
One-liner based on the conditional operator:
var thisval = $(this).val();
ao[id] = thisval === 'true' ? true : (thisval === 'false' ? false : thisval);
One-liner based on || and && behavior:
var thisval = $(this).val();
ao[id] = thisval === 'true' || (thisval !== 'false') && thisval || false;
Shortest one-liner (combination of the above):
var thisval = $(this).val();
ao[id] = thisval === 'true' || (thisval === 'false' ? false : thisval);
Try JSON.parse().
"true" and "false" are actually json representations of true, false. This is how ajax parses json object as a string from server side. If on server side, we return true, false => the browser will receive it as a string "true" or "false" (json representation)
if ( $(this).val() == "true" || $(this).val() == "false") {
ao[id] = JSON.parse($(this).val());
}else {
ao[id] = $(this).val();
}
DEMO