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

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.

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 !!!foo the same as !foo? [duplicate]

This question already has answers here:
The use of the triple exclamation mark
(4 answers)
What is an exclamation point in JavaScript?
(2 answers)
Closed 3 years ago.
Knowing that !!foo gives you the Boolean value of foo, I have seen some programmers say that it's better to use !!!foo instead of !foo because you are changing it to its Boolean value first and then negating the value.
So my question is,
Is !!!foo always equals !foo? (!!!foo === !foo)
Yup. Just for clarity:
!!x === x is not generally true, but it is true if x is already a boolean: "not (not true)" is true, and "not (not false)" is false.
!foo is always a boolean; if foo is truthy, it's false, otherwise it's true.
So if you substitute !foo in for x you get that !!(!foo) === (!foo) is always true. Removing the parentheses doesn't change the meaning, so !!!foo === !foo is always true.
Which means there's no good reason to write !!!foo in actual code. Just use !foo instead.
I've never seen !!!foo used in actual code, but yes, they are always strictly equal.
The extra two exclamation marks just negate the boolean value twice, which always gives the same result.
If foo is set as boolean then !foo will be equal to !!!foo , See the example and screenshot given below
var foo = true;
console.log('foo => '+foo);
console.log('!foo => '+!foo);
console.log('!!foo => '+!!foo);
console.log('!!!foo => '+!!!foo);
console.log('!!!!foo => '+!!!!foo);
if(!!!foo === !foo){
console.log("Equals");
}else{
console.log("Not Equals");
}
While you are correct, !!!foo would equal to !foo, I've never seen JS script using !!!foo before, and I can't think of a good reason to do that. You're gonna create code smell if you write this in your own code.
In other words, don't do that.

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

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.

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.

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