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

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.

Related

Meaning of exclamation before dot [duplicate]

This question already has answers here:
In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?
(5 answers)
Closed 7 months ago.
I've seen somewhere written in the code fixture.componentInstance.dataSource!.data = [];
I want to know the meaning of dataSource!.data
I know about the meaning of question mark(?) before dot(.) like key1?.key2 but an Exclamation(!) before dot(.) !. expression makes me curious.
Many thanks in advance!!
It's called the Non-null Assertion Operator
https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#non-null-assertion-operator-postfix-
It removes null and undefined, allowing you to assert that you know there will be a value. Usually this is a code smell, something that should give you pause to consider other methods so that you can avoid using it. Type narrowing would be preferred. But in some specific instances, this operator can be a useful tool.

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.

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.

Why would I use !! in JavaScript? [duplicate]

This question already has answers here:
What is the !! (not not) operator in JavaScript?
(42 answers)
Closed 8 years ago.
While reading lodash source code, I saw:
this.__chain__ = !!chainAll;
Why would one use !! on the chainAll parameter?
I assume this is a safer way to detect falsy values or dealing w/ different JavaScript versions, but would like to know the scenario it protects.
The !! construct is a simple way of turning any JavaScript expression into
its Boolean equivalent. For exmaple: !!"something" === true, while !!0 === false
DEMO
JS use dynamic type for variable. Thanks to this trick you convert the variable into a boolean if it was not a boolean, an it doesn't modify the value if it was a boolean

String evaluation function in JavaScript [duplicate]

This question already has answers here:
How to convert string equation to number in javascript?
(5 answers)
Closed 8 years ago.
Is there any built-in function in JavaScript like eval built-in function in Python?
notice: eval function take an equation as string and returns result. for example assume variable x is 2, then eval("2x+5") returns 9.
Yes, there is eval function in JavaScript too.
Besides, the statement should be valid for evaluation, i.e. eval("2*x+5").
You should also note, that using eval in JavaScript is not recommended. You can read about at MDN.
REF: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval
Yes, it's called eval, oddly enough.
http://www.w3schools.com/jsref/jsref_eval.asp
Edit: the mozilla link from VisioN (https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval) is better, since it explains why you shouldn't use it.
You can use eval() however you will need to convert any "human" math operators to ones understood by javascript.
var sum = "4x5";
eval(sum.replace("x", "*"));
Update didn't read the part about x being a variable! that does make it slightly more complicated depending on how complex the equations are.

Categories

Resources