Meaning of !! javascript [duplicate] - javascript

This question already has answers here:
What is the !! (not not) operator in JavaScript?
(42 answers)
Closed 7 years ago.
I found some code about authentication with angular and i can't understand this trick :
authService.isAuthenticated = function () {
return !!Session.userId;
};
What does !! mean 'different of userId' ?
whenever true = !!true = !!!!true =>etc, it don't understand this.
Somebody can help me?
(https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec for the source , part 'The AuthService')

!! Converts any value to a boolean value
> !!null
false
> !!true
true
> !!{}
true
> !!false
false
If a value is falsey then the result will be false. If it is truthy the result will be true.
Even more, the third ! inverts the converted value so the above examples become:
> !!!null
true
> !!!true
false
> !!!{}
false
> !!!false
true

It forces what is returned to be a boolean and not an integer or empty value. For example, 0 evaluates to false with == but will not with ===. So to be sure that any integer 0 returned will be converted into an boolean, we use !!. This also works if null or undefined is returned.
So whats happening is actually:
var test = null;
var result = !test; // returns true
result = !return; // returns false

!! is used to convert the value to the right of it to its equivalent boolean value.
!!false === false
!!true === true

Coerces oObject to boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, true.
!oObject //Inverted boolean
!!oObject //Non inverted boolean so true boolean representation
So !! is not an operator, it's just the ! operator twice.
Referred from : https://stackoverflow.com/a/784946/2218635

Related

The result of []==false is true, why? [duplicate]

I have two statements like this. Why do they both evaluate to false?
console.log([] == true)
console.log(![] == true)
If [] == true is false shouldn't ![] == true result to true?
It's the way coercion works.
The first step of coercion is to convert any non primitive types to primitive types, then using a set of rules convert the left, right or both sides to the same type. You can find these rules here.
In your case [] == true, would pass through these 4 steps:
[] == true
[] == 1
"" == 1
0 == 1
Whereas based on operator precedence the ! in ![] == true is executed first so the expression is converted to false == true which is obviously false.
You can try the live demo by Felix Kling to better understand how the sameness operator works.
In more words:
The value ![] is false, because [] is an Object (arrays are objects) and all objects, not including null, are truthy. So any array, even if it is empty will always be a truthy, and the opposite of a truthy is always false. The easiest way to check if a value is a truthy is by using !!.
console.log("![]: " + ![]);
console.log("!![]: " + !![]);
When you are using a loose comparison (using == instead of ===) you are asking the JavaScript engine to first convert the values into the same type and then compare them. So what happens is the values get converted according to a set of rules, once they are the same type, they get compared though the same process as a strict equality check (===). The first change that [] goes through is to get converted to a string, the string version of an empty array is an empty string "", the empty string is then converted to a number, the numeric value of an empty string is 0, since the numeric value of true is 1 and 0 != 1, the final output is false.
console.log("[] == true => `" + ([] == true) + "`");
console.log("String([]) => `" + String([]) + "`");
console.log("Number('') => `" + Number("") + "`");
console.log("Number(true) => `" + Number(true) + "`");
As per the Abstract Equality Comparison Algorithm - http://es5.github.io/#x11.9.3
Types of x and y are checked when x == y is to be checked.
If no rule matches, a false is returned.
For [] == true , rule 7 matches, so a result of [] == ToNumber(true) is returned i.e. false is returned.
Reason you're getting the same result for ![] == true, because ![] returns false, and false == true returns false .
To get opposite result for your second operation, add a precedence (i.e. wrap) to your expression with braces.
console.log(!([] == true)); // returns true
Put ![] in the console. It's false.
So ![] == true is the same as false == true, which is false.
[] != true is true though
None of the answers so far has addressed the main problem. [Edit: This is no longer true. See Nick Zoum's answer.]
The question essentially is this:
[] == true returns false
=> [] is not true
=> [] is false (because something not true must be false)
=> ![] should be true, since negation of false is true. Then why does ![] == true return false?
[] is actually truthy. (So ![] is actually falsy.)
Still, [] == true returns false -- the reason is coercion. It's another of Javascript's gotchas.
When an array is checked for equality explicitly against a boolean value (that is, against true or false), its elements are first converted to strings and then joined together. An empty array therefore becomes "" — therein lies the problem, because an empty string is falsy.
In brief, an empty array is truthy, but it's coerced (when being compared to a boolean value) to an empty string, which is falsy.
Note the following, which comes from https://www.nfriedly.com/techblog/2009/07/advanced-javascript-operators-and-truthy-falsy/
Arrays are particularly weird. If you just test it for truthyness, an
empty array is truthy. HOWEVER, if you compare an empty array to a
boolean, it becomes falsy:
if ( [] == false ) {
// this code runs }
if ( [] ) {
// this code also runs }
if ([] == true) {
// this code doesn't run }
if ( ![] ) {
// this code also doesn't run }
(This is because when you do a comparison, its elements are turned to Strings and joined. Since it's empty, it becomes "" which is then falsy. Yea, it's weird.)
Read https://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/
Rule in JavaScript for The Equals Operator (==)
if
type(x) type(y) result
1.x and y are the same type See Strict Equality (===) Algorithm
2.null Undefined true
3.Undefined null true
4. Number String x == toNumber(y)
5. String Number toNumber(x) == y
6. Boolean (any) toNumber(x) == y
7. (any) Boolean x == toNumber(y)
8.String or Number Object x == toPrimitive(y)
9.Object String or Number toPrimitive(x) == y
***10.otherwise… false

Why is !!'0' == true when '0' == false [duplicate]

This question already has answers here:
In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?
(15 answers)
Closed 3 years ago.
The question says it all as I understand !!false = false
Then if
0 == false // true
'0' == false // true
why
!!0 == false
!!'0' == true
string zero ('0') is a truthy value
!!'0' == true
!'0' -> !false -> true
So you're actually doing
true == true
It looks like you stumbled across the importance of the === operator.
'0' == false; // true
'0' === false; // false
Boolean('0'); // true
typeof('0'); // string
typeof(!'0'); // boolean
!'0' === false; // true
!!'0' === false // false
The first negation converts string '0' to a boolean by calling of abstract function ToBoolean. According to JavaScript specification, only 7 values are evaluated/coerced/converted to false i.e are falsy:
null, undefined, NaN, Empty String, +0, -0, and false.
So, '0' is evaluted to a truthy, !'0' to false and !!'0' to true.
PS: Another cases of why '0' == false is evaluated to true is raised after the original question by the OP in a comment below. Even though not relevant to the original post, here is the explanation:
In the specification, section Abstract Equality Comparison reads: "When evaluating x == y, if the type of y is Boolean, first convert y to Number and then do the comparison again".
So Number(false) is evaluated to 0. In the next comparison run, string '0' is compared with number 0 i.e '0' == 0. The spec says convert the string to number and do the comparison again: 0 == 0.

How does this function work in particular?

Can someone explain me how this function works? I know the ternary operator, so I understand the part, that he checks if flag is true, and if not then use the 2. value. But I don't understand why flag is a Boolean in the first place and why it switches from true to false and vice versa when animate() is being called...
flag = $texte.data('animToggle');
$texte.data('animToggle', !flag);
$texte.animate({
'left': flag ? '-51%' : '0'
})
JavaScript has truthy and falsy values. These are values which equate to true and false when evaluated as Boolean. This means that true and false aren't the only values which can represent true or false data.
For example, if $texte.data('animToggle') is equal to 0 it will be falsy as 0 is a falsy value.
Example 1: 1000
1000 is a truthy value, so this will output "True":
var flag = 1000;
console.log(flag ? "True" : "False");
> "True"
Example 2: ""
"" (empty string) is a falsy value, so this will output "False":
var flag = "";
console.log(flag ? "True" : "False");
> "False"
The ! (Logical NOT) operator converts a value to Boolean and negates it. $texte.data('animToggle', !flag); sets the animToggle data property of $texte to the opposite of what it previously was.
!true // False
!1000 // False
!false // True
!"" // True

How safe is using var t=!0 / var t=!1 for true / false? Do they always return true boolean true / false?

Many of us have seen / use the following:
var t=!0; (t will equal true)
var t=!1; (t will equal false)
How safe is this method of evaluating true / false?
I see google use this all the time.
Will these ALWAYS return a boolean true / false?
Thanks.
Yes:
11.4.9 Logical NOT Operator ( ! )
The production UnaryExpression : ! UnaryExpression is evaluated as
follows:
Let expr be the result of evaluating UnaryExpression.
Let oldValue be ToBoolean(GetValue(expr)).
If oldValue is true, return false.
Return true.
Source: http://es5.github.com/x11.html#x11.4.9
Yes, they'll always return true and false.
More specifically, !x will return true for any "falsey" value (undefined, "", etc) and conversely return false for any "truthy" value.
A more common idiom is !!x which converts any "falsey" value to strictly false and any "truthy" value to strictly true - in other words it's like a "type cast" to a boolean.

What is the "!!" operator in Javascript? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the !! operator in JavaScript?
Sorry if this one is obvious but I can't google it.
What is the "!!" operator in Javascript? e.g.
if (!!window.EventSource) {
var source = new EventSource('stream.php');
} else {
// Result to xhr polling :(
}
Did the author just use "!" twice i.e. a double negation? I'm confused because this is in the official doc.
It will convert anything to true or false:
!!0 // => false
!!1 // => true
!!'a' // => true
!!'' // => false
!!null // => false
Technically, !! is not an operator, it is just two ! operators next to each other. But a double-negation is pointless unless you are using !! like an operator to convert to Boolean type.
In most languages, !! is double negation, as ! is negation. Consider this:
# We know that...
!false == true
# And therefore...
!!false == false
!!true == true
It's often used to check whether a value exists and is not false, as such:
!!'some string' == true
!!123 == true
!!myVar == true
!! is used to convert a non-zero/non-null value to boolean true and a zero/null value to false.
E.g. if a = 4, then !a = false and !!a = !(!a) = true.

Categories

Resources