I have recently read some code that uses !! to convert a variable to boolean for evaluation in an if statement. This seems somewhat redundant to me as the variable would be evaluated for its boolean value anyway. Are there any performance benefits to doing this or is it for better browser support?
Sample Code:
var x = 0;
var atTop = x===window.scrollY;
if(!!atTop){
alert("At the top of the page.");
}
Edit:
I have also seen this for operands that are not of boolean types, but I had always assumed that using if would evaluate the boolean value of the variable anyway as all values in Javascript are either "truthy" or "falsey".
Sample Code:
var x = 1;//or any other value including null, undefined, some string, etc
if(!!x){//x is "truthy"
//wouldn't using if(x) be the same???
console.log("something...");
}
Short answer: No, there is no reason.
In your code, it's already a boolean type, there is no need to convert, and convert it back again: you will always get the same result. Actually, if you have a boolean value (true or false), when you use !! with any of them, it will be converted back to its original value:
console.log(!!true); // Will always be "true"
console.log(typeof !!true); // It's still a "boolean" type
console.log(!!false); // Will always be "false"
console.log(typeof !!false); // It stills a "boolean" type
Answer for edited question: Yes, it's the same. That's what if(...) actually does - it's trying to convert any type to boolean.
Here is a small test, you can play around with that and add whatever you want inside the initialArr array in order to test whether it behaves the same with if and !!:
const initialArr = [
undefined,
null,
true,
false,
0,
3,
-1,
+Infinity,
-Infinity,
Infinity,
'any',
'',
function() { return 1 },
{},
{ prop: 1 },
[],
[0],
[0, 1]
];
function testIsTheSame(arr) {
let equolityCounter = 0;
arr.forEach(item => {
let ifStatement = false;
let doubleNotStatement = !!item;
if (item) {
ifStatement = true;
}
if (
ifStatement === doubleNotStatement &&
typeof ifStatement === typeof doubleNotStatement
) {
equolityCounter++;
}
});
console.log(`Is the same: ${equolityCounter === arr.length}`);
}
testIsTheSame(initialArr);
I would say it was mostly done for code-readability. I doubt there is any significant performance nor compatibility implications (someone feel free to test this please)
But in the code-readability aspect, it would imply to me that this variable previously was not a boolean, but we want to evaluate it as one, if you add new logic concerning this variable, keep that in mind.
Although in your case its already boolean, so its 100% redundant, but I'd guess just a habit of someone for the above reasoning applied excessively, and/or seeing it elsewhere and copying that pattern without fully understanding it (short story time: in C# you can name a protected term a variable name by adding #, so var #class = "hello";, a junior dev just assumed all variable names needed # in front of them, and coded that way. I wonder if someone assumed that an if without a comparison operator needs to have !! in front of it as a comparison operator)
There isn't any run-time benefit (or an objective one) whatsoever to doing this in an if statement. The evaluation performed by the if statement will yield precisely the same result as the evaluation produced by double exclamation mark. There is no difference.
Double exclamation marks is a useful expression to ensure boolean value based on truthyness. Consider, for instance:
var text = undefined;
console.log(text); // undefined
console.log(!!text); // false
// It would make sense here, because a boolean value is expected.
var isTextDefined = !!text;
// It would also affect serialization
JSON.stringify(text); // undefined (non-string)
JSON.stringify(!!text); // "false"
I suppose that this is a habit that was picked up because of the above use cases, thus always converting to boolean when wishing to address a variable's truthyness. It's easier for us (humans and programmers) to follow a rule when it's always applied. You'll either use the blinkers in your car all the time, even when there's nobody around, or it's likely that you'll occasionally (or maybe often) forget to signal when you should have.
It all depends on the value of atTop variable. Follow the discussion here.
In summary, if the value of atTop is anything different to a boolean, the first negation will convert it to a boolean value (negated). Second negation will return the boolean value to the equivalent boolean of the original atTop value.
For example, if atTop is undefined, first ! will turn it to boolean true, then the second ! turns it to boolean false (which would be the equivalent boolean of undefined)
However, in your code the atTop value is the result of an strict equality ===, which means you always get a boolean as a result in atTop. Thus, you don't need to convert a non-boolean value to boolean, and so, the !! is not needed.
Related
can i use the check to find out if yourName variable is false, instead of using the negation operator to change its type.
let yourName;
do {
yourName = prompt("Who are you?");
}
while (!yourName);
console.log(yourName);
the results are the same
Out of the past 5 years of professional enterprise work I've never once seen a do..while loop simply because while() works just fine I understand in certain scenario's you'd want at least 1 loop but in those cases look to see how you're triggering this function. I can only see a small snippet of it but I wouldn't recommend using this.
JavaScript has a fun time with if, while when applying the negation operator.
There's plenty of information on this topic, typically I like to reference MDN for new devs to JavaScript as Mozilla has great tutorials https://developer.mozilla.org/en-US/docs/Glossary/Truthy.
If yourName is of type undefined or null or false or "" it'll be fine but be careful as there's times when you want to check if 0 value is true. It will return false since it's interpreted 0 as false, example you want to check if value does equal zero if(0) will return false. But if(yourName == 0) and yourName is 0 it'll return true.
There's a fun bit with double vs triple equality comparisons in JavaScript as well https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
What is the purpose of adding a negation operator in the while condition
To make sure the value is not an empty string "", undefined, or null.
Can i use the check to find out if yourName variable is false, instead of using the negation operator to change its type
yes you can check to see if yourName is false and it'll work fine without negation it's just a shortcut.
I don't understand what you mean by change its type?
Before explaining the purpose of the negation (!) in the while statement, we must back up and understand while loops.
while will continue to loop (repeatedly run the code within the brackets) when the condition evaluates to true.
while(true){
// this will run forever
}
When the condition evaluates to false the looping stop.
while(false) {
// this will never run
}
We can use a variable for a boolean evaluation based on "truthyness".
Truthyness: A funky thing in javascript where boolean evaluations can recognize nil things like 0, null, undefined, "" as "false", and existing things like 1, "something", object, array -- anything that "is" or has a value as "true".
var bob = true;
while(bob) {
// this will run one time.
bob = false;
}
You can flip things around using the ! operator:
var bob = false; // <-- this is opposite of above
while( ! bob ) { // <-- so we'll use the ! to flip it
// this will run one time.
bob = true;
}
So the tricky part is that the "negation" operator leverages the funky "truthiness" understanding in the language... we can leverage this and "flip" truthiness entities like string, array, object to check if they "are" or "are not".
So based on our understanding of "truthyness" we can say:
var bob = "silly";
bob == true; // true
!bob == false; // true
var sally = 0;
sally == false; // true
!sally == true; // true
NOTE: Strict type evaluation is handled through triple equals === and !==
Now to the point (let's make things simpler):
let yourName;
while ( ! yourName ) {
// "prompt" will
// 1. Block all javascript execution, including this while loop.
// 2. Return null (falsy) or a text string (truthy)
yourName = prompt("Who are you?");
}
So in the above, we are preventing the script from execution until the prompt returns a valid name.
The purpose is to execute a statement while Boolean expression evaluates to false
!false === true
This question already has answers here:
When to use the double not (!!) operator in JavaScript
(2 answers)
Closed 6 years ago.
I've recently started using double exclamation points !! before an object to make sure that it's not null and that it's not undefined and not an empty string, to make sure that I encompass all the different ways that a variable can be empty.
Is this necessary? It's hard to read, for instance:
if(!!name) vs if(name)
Any opinions on this? I want my code to be safe and not get into conditions where a null pointer exception and other things can occur, but I also want my code to be readable.
What you're doing is already done by JavaScript natively.
if( value ) {
}
will evaluate to true as long as value is not:
null
undefined
NaN
empty string ("")
0
false
Check out the toboolean conversions in the specification.
No, there's no need at all for the double-bang if you're using the variable as the condition in an if. Simply if (name) is sufficient to ensure that name is not a falsy value. All object references are truthy; null is falsy.
This is completely unnecessary unless you need a strict comparison to boolean true, for example:
switch (true) {
case foo:
Should be
switch (true) {
case !!foo:
Or alternatively, the verbose but more readable Boolean(foo) (don't use new with the primitive constructors). Note that opposite is not true, if you are testing for falsey values then it becomes a problem because 0, NaN and the empty string, which may be valid values, are falsey:
if (!foo) { // foo had better not be empty string or zero
However, JavaScript offers you an out here (that some frown on) involving loose equality, null and undefined are loosely equivalent to each other but not to any other falsey values:
null == undefined //true
null == NaN // false
undefined == '' // false
Totally and completely ... pointless, to use a small pun.
The if() autmotically converts the conditional value to a boolean.
The !! converts it a boolean as well.
Where !! is sometimes used is to force something to a boolean value..
Such as:
var hasElement == !!document.getElementById("zz");
I have a question concerning some concepts in JavaScript such as (truthy, true) and (falsy, false).
I know the type of 1 is not true but the question is: why 1 == true?
What was the main reason of ECMAScript to consider 1 or "ghsagh" as true?
I also cannot understand the meaning of truthy and falsy.
What was the benefit of this consideration?!
JavaScript likes to convert values to other types implicitly whenever possible. Because of that, when comparing booleans to other types of variables, JavaScript uses the same logic as older programming languages. A value that represents empty, null, or zero (such as 0, or "") evaluates to false, and any other value (such as 1, 5, -19, "ghsfsah", or other meaningful content) evaluates to true.
Why does it do this? Well for one it allows developers a small shortcut when checking to see if a variable has content. For example, if a user doesn't give input in a text field, we can easily check to see if a field is empty and prompt the user.
if ( !textfield.value ) {
alert( "Please enter something in the text box" );
}
If you need to see if something is actually true or false, you can use ===.
JavaScript is very flexible about the types of values it requires. If JavaScript wants a boolean, it will convert whatever value you give it to a boolean.
Some values (“truthy” values) convert to true and others (“falsy” values) convert to false.
The following values convert to, and therefore work like, false:
undefined
null
0
-0
NaN
"" // the empty string
All other values, including all objects (and arrays) convert to, and work like, true.
As an example, suppose that the variable o either holds an object or the value null. You can test explicitly to see if o is non-null with an if statement like this:
if (o !== null){
....
}
The strict not-equal operator !== compares o to null and evaluates to either true or false. But you can omit the comparison and instead rely on the fact that null is falsy and objects are truthy:
if (o){
....
}
In the first case, the body of the if will be executed only if o is not null. So the code block will execute even if o is set to undefined.
The second case is less strict: it will execute the body of the if only if o is not false or any falsy value (such as null or undefined). Which if statement is appropriate for your program really depends on what values you expect to be assigned to o. If you need to distinguish null from 0 and "", then you should use an explicit comparison.
I'm trying to learn JavaScript by going through some code in an application and I keep seeing !variable in if conditions. For example:
if (!variable.onsubmit || (variable.onsubmit() != false)) {
What is it? Some kind of test if the variable is empty?
! is the logical not operator in JavaScript.
Formally
!expression is read as:
Take expression and evaluate it. In your case that's variable.onsubmit
Case the result of that evaluation and convert it to a boolean. In your case since onsubmit is likely a function, it means - if the function is null or undefined - return false, otherwise return true.
If that evaluation is true, return false. Otherwise return true.
In your case
In your case !variable.onsubmit means return true if there isn't a function defined (and thus is falsy), otherwise return false (since there is a function defined).
Simply put - !variable means take the truth value of variable and negate it.
Thus, if (!variable) { will enter the if clause if variable is false (or coerces to false)
In total
if (!variable.onsubmit || (variable.onsubmit() != false)) {
Means - check if variable.onsubmit is defined and truthy (thus true), then it checks if calling onsubmit returns a result that coerces to true. In a short line it checks if there is no onsubmit or it returns true.
Next time, how do I find this myself?
MDN has a list of operators here.
The language specification specifies such operators, though being the official specification it does contain some jargon which might be hard to understand.
It is a negation operator used for truth tests on a variable.
var myVariable = 1;
if ( ! myVariable )
{
// myVariable evaluates as false
}
if ( myVariable )
{
// myVariable evaluates as true
}
The selected answer already answers the question. One thing to add in this is that ! operator can be used in a rather interesting fashion.
obj = {}
if (!!obj) {console.log('works')} // !!obj = true
obj = undefined
if (!!obj) {console.log('does not work')} // !!obj = false
So double !! will change any expression to a boolean value with no exceptions.
This has a very peculiar use case in some cases.
Lets say there is a function that returns either true or false and nothing else. In that case one could just change return returnValue to return !!returnValue for extra caution (although not need in most of the cases)
Conversely, if a function only accepts true or false and nothing else, one could just call the function as functionA(!!parameter) instead of functionA(parameter), which again is not needed in most of the cases, but could ensure extra security
! is a logic reversal operator, if something was true it will change it to false, if something is false, it will change to true.
example, we know that empty string or 0 in boolean is false.
let a = Boolean("")
console.log(a) // shows false, because empty string in boolean is false
console.log(!a) // shows true, because logic is reversed
easier example:
let a = 5
let b = 1
let c = a > b
console.log(c) // shows true, since a,5 is bigger than b,1
console.log(!c) // shows false, since logic is now reversed
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.
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;
}
...
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.
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.
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.
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.
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.
Since the checked value is Boolean it's preferred to use it directly for less coding and at all it did same ==true
Since you already initialized clearly as bool, I think === operator is not required.
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:
It does not usually add to the meaning of the expression - that's in cases where the value is known to be boolean anyway.
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).
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.
Also can be tested with Boolean object, if you need to test an object
error={Boolean(errors.email)}
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.
Revisa https://www.w3schools.com/js/js_comparisons.asp
example:
var p=5;
p==5 ? true
p=="5" ? true
p==="5" ? false
=== means same type also same value
== just same value