Why "if(!!variable)" instead of "if(variable)"? [duplicate] - javascript

This question already has answers here:
What is the difference between if(!!condition) and if(condition)
(3 answers)
When to use the double not (!!) operator in JavaScript
(2 answers)
Why use if (!!err)?
(3 answers)
Closed 6 years ago.
In someone else's code I found this way to test the existence of a variable :
if(!!variable) {
//Do something
} else {
//Something else
}
Is there a reason to test with if(!!variable) instead of if(variable) ? Is it a good practice?

Is there a reason to test with if(!!variable) instead of if(variable)?
No.
Using if() will coerce the condition to a boolean anyway, there's no need to manually do it. Using this sort of syntax makes sense when you want to guarantee you've got a boolean elsewhere, for example if you wanted to log the truthiness of the expression:
console.log(!!variable)
This will ensure that you get either true or false logged, rather than the original value of the variable. But inside an if? It makes no difference.

No, in the case of a if, their is usually no reason to write that in JS.
I would not call it bad practice, since it can often come from programmer coming from strongly typed language, and is a common quick way to do the conversion to bool in thoses language.
It can also be used to emphasise the importance of the truthiness of the value in a long if, and show the programmer didn t forget to put the condition.
TL:DR: As for a lot of things: it may not be good practice, but it only become bad practice if your team is not used to that practice, either train them, document, or leave it.

Double negation is a bit of a hacky way (IMHO) to convert a variable to bool. using ! on variable coerces it to a bool and negates it, and using it again convert it back to the 'correct' value. So !!0 === false
As mentioned by James there is no reason to do this inside an if statement. The only reason really to do this would be to coerce to a bool for logging purposes or similar so the value logged is true or false rather than 0, an empty string etc

Double ! (!!) is not an operator. It's just ! twice - double negation.

Related

Using !! in if statements [duplicate]

This question already has answers here:
What is the !! (not not) operator in JavaScript?
(42 answers)
Closed 2 years ago.
I have come across code in a web app where it uses !!, I was told that this enforces a check for true or false instead of truthy or falsy. Is this correct?
if (!!this._currentItemIndex) {
this._findItemByCurrentIndex();
}
I have been having trouble finding any resources online to explain this.
Normally you'll see code like:
let x = !!y;
Where this is casting whatever value y has into a simple true or false outcome, a boolean. This is often employed to avoid retaining references to things you don't need, like y could be a complex structure but you don't care about the details, you just want to track if it was assigned.
It's unusual to see this employed in an if since it really doesn't do anything useful. It converts to a boolean, but if will anyway. This is just junk code.
It might as well be if (!!!!!!!!!!!!!!!!!!!!x) for all the good it does.
A better version would look like:
if (this._currentItemIndex) {
// Some non-zero value was assigned
}
Or if it is populated:
if (this._currentItemIndex > 0) {
// Communicates intent better
}

Is using == instead of === ok for null/undefined? [duplicate]

This question already has answers here:
How can I determine if a variable is 'undefined' or 'null'?
(34 answers)
Which equals operator (== vs ===) should be used in JavaScript comparisons?
(48 answers)
Closed 3 years ago.
I currently have a variable that can be null as well as undefined. In both cases I want to leave the function:
if (myvar==null) return;
this works fine but I retrieve warnings from my IDE (VS) because == does not care about the type while === does. I am aware that == is generally be seen as bad style because of this.
Is this the exception from the rule? Should I simply ignore this warning and stick to the better readability or would the following be the recommend action?
if (myvar===null || myvar===undefined) return;
The problem is the lack of clarification.
If you're writing the code for yourself, it's fine as you know exactly what you're doing. But if a contributor find this code, they could either:
Not knowing how == works in case of null / undefined
Knowing how it works but not knowing if the use was intentional (if you actually want to check both null or undefined, or you wanted just check for null but used ==)
The code should be clear, so often you find programmers adding comments before this check to specify that yes, they know what they're doing, and yes, it was intentional.
Eventually you get tired of that and start to use myvar === null || myvar === undefined.
It's more verbose, but it's clearer, and doesn't give room to misunderstanding.
Another thing I notice is creating custom fuction for such things, e.g. isNil(myvar) but despite the verbosity I prefer checking both values.
== has very specific rules, and it normally recommended against because those rules are not intuitive. I would only condone using it if you have memorized the rules related to its behavior, as have all other devs who could possibly have to deal with your code (which most have not).
In this case, a == null returns true if a is one of null, undefined, or document.all, but not the other 4 falsely JS values (MDN, including why document.all is falsely). So unless you want it to match document.all, I would use ===.
Additionally, using === in all places adds consistency to your code.

Double-negation + logical and in Javascript [duplicate]

This question already has answers here:
Why don't logical operators (&& and ||) always return a boolean result?
(9 answers)
Closed 7 years ago.
I just ran across this code
var someBool = !!(o.a && o.a.t);
I was about to remove the double-negation, then realized it forces someBool to be a boolean value... Looking on the MDN, I find this example
a5 = "Cat" && "Dog"; // t && t returns "Dog"
This seems atypical based on my experience in other languages. I'd expect the logical and operation to always return a boolean value. Can anyone explain why this use case is supported in Javascript?
Also, is the code that sent me in this direction the best way to force a bool around logical and? I'm aware of new Boolean, but that doesn't return a primitive type like the double-negation, so perhaps that's the way to go?
The && and || operators have an effect similar to boolean AND and OR, but they don't affect the expression value. The expressions are evaluated and the values tested with the JavaScript "truthiness" rules, but the overall expression value is that of the actual operand expressions (well, one of them).
Yes, that's different from C and Java and etc. JavaScript is a different language with its own rules.
The Boolean constructor can be called without new to perform a "truthiness" test and return a boolean primitive. Using !! is fairly idiomatic however.

Why is the !! preferable in checking if an object is true? [duplicate]

This question already has answers here:
What is the difference between if(!!condition) and if(condition)
(3 answers)
What is the !! (not not) operator in JavaScript?
(42 answers)
Closed 8 years ago.
Some JavaScript examples use !! to check if an object is available
// Check to see if Web Workers are supported
if (!!window.Worker) {
// Yes, I can delegate the boring stuff!
}
Why is this preferred to just if (window,Worker) and in what context would this fail?
It isn't preferable, or even different, in this case. The double-bang converts the variable that follows it into a Boolean value (similar to wrapping in the Boolean() constructor). Gets around potential problems with truthy and falsey variables.
However, putting the variable alone in an if() clause does the same thing (it also resolves the contents of the if's parens to a hard Boolean).
The double-bang can prove helpful in other cases, such as if you want to return a true or false at the end of a function based on a variable's truthiness/falsiness. That would be rather than:
if(condition) {
return true;
} else {
return false;
}
You could simply write:
return !!condition;
It isn't.
!! is useful when you are passing an object into a function that (like jQuery's toggle()) checks to see if its argument is a boolean, or when the function might stash its argument and thereby prevent the object from being collected.
The case you cite is neither of those. Use a bare if.
In the condition of an if statement both versions will do the same thing and its a stylistic choice. Some people prefer use !! to highlight that Worker is not a boolean and is being converted tto boolean.

difference between if (!!variable), and, if (variable)? [duplicate]

This question already has answers here:
Can someone explain this 'double negative' trick? [duplicate]
(9 answers)
Closed 9 years ago.
Is there any difference (in JS) between using the double negative !! and not using it at all?
For example
if (!!variable){... vs. if (variable){...
I know there are times where I've gotten a warning using the 2nd method..
When should each be used? and when will each throw a warning in the console? (for variables, objects, arrays etc.)
Thanks!!
There is a difference for assigning it, but not for using it in a conditional statement. The reason the !! is used is because the first ! will convert your variable to its truthy evaluation and then not it. So "hello" becomes true, is then negated, becomes false, and the second ! will negate the false, resulting in true. This can be desirable when trying to obtain the thruthy value from a variable. However, there is not much gained by doing it in an if statement.
In this particular case, there is no difference. In fact, !!variable is wasteful.
However in more general cases, it casts the variable to a boolean. Personally I've only found this useful when debugging, and to learn what values are truthy and falsy.

Categories

Resources