How does this function work in particular? - javascript

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

Related

Is 0 considered true in ES6?

Is 0 considered true in ES6? Or all strings considered true?
this is returning true:
var value = "0";
var isTrue = value ? true : false; // true
I thought === was for strict equality.
If it has changed is there a way to get the old way for compatibility sake?
UPDATE:
Thanks. The value I'm receiving will always be a string so I'll check for "0" and "false":
var booleanValue = value && value!=="0" && value!=="false" ? true : false;
"0" is true because it's just a string and has a value, but the 0 as a number is considered false
This is a list of all falsy values in javascript:
false
0
'' or ""
null
undefined
NaN
Only the String '' is a falsy value, meaning that it is an empty string.
'0' is a string with content so it isn't a falsy value, but 0 is one.
All strings that have characters in them are truthy.¹ Only the empty string, "", is falsy.¹
0 (the number) is falsy. "0" is not.
I thought === was for strict equality.
It is. There is no === check in your code. The conditional operator (? :) doesn't do an === check on the condition operand. It does a boolean check, just like if does.
If you used ===, it you'd get false:
var isTrue = value === true ? true : false; // false
Of course, in that case, there's no point to the conditional operator:
var isTrue = value === true; // false
The value I'm receiving will always be a string so I'll check for "0" and "false":
var booleanValue = value && value!=="0" && value!=="false" ? true : false;
It depends on what you want to do and what possible values you might get. For instance, if what you're getting will be a string containing a valid number or a valid boolean (as seems the case from your example there), you could use JSON.parse to parse it to a number or boolean:
var isTrue = !!JSON.parse(str);
(The !! is so that 0 and NaN convert to false and a number that isn't 0 or NaN converts to true.) But again, it depends on what you're receiving, a switch with the values you're expecting may be better, etc.
¹ "falsy" and "truthy":
"falsy" - coerces to false when used as a boolean, such as in a conditional operator as in your question. The falsy values are 0, NaN, null, undefined, "", and of course, false.
"truthy" - coerces to true when used as a boolean. All non-falsy values are truthy, including "0" and "false".
You're inspecting a string containing 0 instead of an actual number 0.
"0" // string
0 // number
A string is considered false if it is equal to '', all other strings are considered true
A number is considered false if it is either 0 or NaN, all other numbers are considered true.
=== indeed means strict equal, meaning a comparison is made on both type and value. So:
true == 1 // true
true === 1 // false
Actually its other way around, for any string, it will return True, for 0 as an integer, it will return False, and for 1 as an integer, it will return True
var value0 = 0;
var value1 = 1;
var str = "23123";
var isTrue0 = value0 ? true : false;
var isTrue1 = value1 ? true : false;
var isTrueStr = str ? true : false;
console.log('0: ' + isTrue0);
console.log('1: ' + isTrue1);
console.log('string: ' + isTrueStr);
isTrue = value - classic error using assignment rather than comparison.

Meaning of !! javascript [duplicate]

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

Why does parseFloat('0.0') or parseInt('0.0) returns false

While parsing the inputs i came across this behaviour of javascript
if you parse a number
console.log(parseFloat('562.0') ? 'true' : 'false')
console.log(parseInt('562') ? 'true' : 'false')
It returns true, but if i parse 0
console.log(parseFloat('0.00') ? 'true' : 'false')
console.log(parseInt('0') ? 'true' : 'false')
it returns false
can any one please explain why this happens ??
When you use the conditional operator ? :, according to ECMA-262 §11.12, the first operand (in your case it's the Number returned byparseInt or parseFloat) is converted to Boolean.
Conversion goes according to ECMA-262 §9.2, which says
Number - The result is false if the argument is +0, −0, or NaN; otherwise the result is true.
That's why your expressions with 562 evalute to true, and expressions with 0 evalute to false.
it doesent return boolean false it return number 0 in ternary operator you compare with 0. 0 is false
Actually it returns 0. But, in javascript zero means false.
0 and 1 is boolean. http://en.wikipedia.org/wiki/Boolean
console.log((true)+0); // 1
console.log((false)+0); // 0
Zero is the only number returns false.
console.log((1) ? "true" : "false"); //true
console.log((0) ? "true" : "false"); //false

how come ![] is not true?

Was just playing around with nodejs and chrome's console when I tested this:
[] == true // false
![] == true // false
!![] == true // true
How come? Isn't it wrong?
See the ECMAScript standard:
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.
9.2 ToBoolean
The abstract operation ToBoolean converts its argument to a value of type Boolean according to Table 11:
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.
The result is false if the argument is the empty String (its length is zero);
otherwise the result is true.
Object → true
An array is an Object.
It has to do with how the browser handles implicit conversions in JS.
As [] is an empty array, it evaluates to false:
[] == true
false == true
However, noting it, will turn the object into a boolean with a value of false:
![] == true
false == true
However, boolean([]) will return true.
However, noting that, will turn it into a boolean with the value of !false:
!![] == true
!false == true
true == true
This is why implicit conversions arn't recomended unless needed:
"1" == true
true == true
"1" === true
false
[] == true is false because [] is not equal to true, just like "some string" is also not equal to true.
![] == true is false because [] evaluates to a true value when used in a conditional statement:
if([]) console.log('[]');
if(![]) console.log('![]');
// the result will be '[]' because [] will evaluate to true
// in a conditional even though it doesn't equal true
Another thing that may help you to think about it is ![] == false will be true.
!![] == true is true because !! converts anything to a true or false value based on whether it would be true or false in a conditional statement. So if(obj) and if(!!obj) will always have the same result.

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.

Categories

Resources