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

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.

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

Can someone explain this simple concept of null and undefined, more specifically single double & triple equals, or can you link the best explanation [duplicate]

This question already has answers here:
why null==undefined is true in javascript
(6 answers)
Closed 1 year ago.
How is null equal to undefined and not equal to undefined within the same operator.
undefined == null
true
undefined !== null
true
undefined === null
false
undefined != null
false
== converts the variable values to the same type before performing the actual comparison(making type coercion)
=== doesn't do type coercion and returns true only if both values and types are identical for the two variables being compared.
Let's take a look at some examples:
console.log(5 == "5"); // no type coercion is being made - hence, the result is true.
console.log(5 === "5"); // type coercion is being made, value is the same but the data types are not (number vs string);
console.log(undefined == null); // should be true because type coercion is not being made and the data values are both falsy!
console.log(undefined !== null); // should be true cause type coercion is being made and the data types are differnt!
console.log(undefined === null); // // should be false cause type coercion is being made and the data types are differnt.
console.log(undefined != null); // should be false cause type coercion is not being made and the data values are both falsy!
Undefined and null are empty variables. But to understand whats above you have to understand comparison operators. == is a comparison operator that can convert. === really tests if its the same without doing type conversion. So null is practically the same as undefined. Its a bit hard to understand when you first think about it but its really not that hard. Some examples:
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
Please find my answer below.
"==" coerces the type of the variable before making a comparison.
i. so undefined == null is true since both the variables coerces to false (since they both indicate an empty value) and post that comparison is made making them equal.
!== makes a strict comparison so the type is not changed, in case of undefined the type is "undefined" and in case of null the type is "object" which can be verified using typeof.
ii. so since the type does not match,!== return true i.e. undefined !== null.
iii. Same way === makes a strict comparison, so undefined === null is false, since the type is only different
iv. Lastly undefined != null is false, since != like == coerces the type of the variables to false, and then compares. Hence they both seem equal to != and it return false.

Why do both "[] == true" and "![] == true" evaluate to false?

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

JavaScript: How '' == '0' // false and 0 == '' //true? [duplicate]

This question already has answers here:
Implied string comparison, 0=='', but 1=='1'
(6 answers)
Closed 7 years ago.
I am curious how
'' == '0' // false
left side is a blank string and right side has string with value 0 so its fine its is false.
But
0 == '' // true
how blank string equals to zero, both are typed different as well as value.
similar
false == 'false' // false
left is false , but we are not equating (===) type of value , its just has value false so it should be true ? but why it is false.
Could we explain the same ?
The left operand is of the type Number.
The right operand is of the type String.
In this case, the right operand is coerced to the type Number:
0 == Number('')
which results in
0 == 0
The following values are always falsy:
false 0 (zero)
"" or '' (empty string)
null
undefined
NaN (a special Number value meaning Not-a-Number!)
I found a nice table explaining what works and what not with the == operator.
Here is the link to the tables also containing === and if().

How does Type Coercion in Javascript in the case of object to boolean?

To the best of my knowledge, (x == false) should do the same thing as !x, as both of them try to interpret x as a boolean, and then negates it.
However, when I tried to test this out, I started getting some extremely strange behavior.
For example:
false == [] and false == ![] both return true.
Additionally
false == undefined and true == undefined both return false, as does
false == Infinity and true == Infinity and
false == NaN and true == NaN.
What exactly is going on here?
http://jsfiddle.net/AA6np/1/
It's all here: http://es5.github.com/#x11.9.3
For the case of false == []:
false is converted to a number (0), because that is always done with booleans.
[] is converted to a primitive by calling [].valueOf().toString(), and that is an empty string.
0 == "" is then evaluated by converting the empty string to a number, and because the result of that is also 0, false == [] is true.
For the case of false == ![]:
The logical not operator ! is performed by returning the opposite of ToBoolean(GetValue(expr))
ToBoolean() is always true for any object, so ![] evaluates to false (because !true = false), and therefore is false == ![] also true.
(false == undefined) === false and (true == undefined) === false is even simpler:
false and true are again converted to numbers (0 and 1, respectively).
Because undefined cannot be compared to a number, the chain bubbles through to the default result and that is false.
The other two cases are evaluated the same way: First Boolean to Number, and then compare this to the other number. Since neither 0 nor 1 equals Infinity or is Not A Number, those expressions also evaluate to false.
The abstract equality algorithm is described in section 9.3 of the specification.
For x == y where x = false and y = []:
Nope. Types are not equal.
Nope, x is not null.
Nope. x is not undefined.
Nope, x is not a number
Nope, x is not a string.
Yes, x is a boolean, so we compare ToNumber(x) and y.
Repeat the algorithm, x=0 and y=[].
We end at step 8:Type(x) == number. and Type(y) == object.
So, let the result be x == ToPrimitive(y).
ToPrimitive([]) == ""
Now, repeat the algorithm again with x=0 and y="". We end at 4: "return the result of the comparison x == ToNumber(y)."
ToNumber("") == 0
The last repetition of the algorithm ends at step 1 (types are equal). By 1.c.iii, 0 == 0, and true is returned.
The other results can be obtained in a similar manner, by using the algorithm.
false == []
Using == Javascript is allowed to apply conversions. The object will convert into a primitive to match type with the boolean, leaving an empty string. The false will convert into a number 0. The compares the empty string and the number 0. The string is converted to a number which will be 0, so the expression is "true"
![]
Javascript converts the object to the boolean true, therefore denying true ends being false.
false == undefined true == undefined
false == Infinity and true == Infinity
false == NaN and true == NaN
Again a bit of the same! false is converted to 0, true to 1. And then, undefined is converted to a number which is... NaN! So false in any case
I would recommend to use === !== as much as you can to get "expected" results unless you know very well what you are doing. Using something like Boolean(undefined) == false would also be nice.
Check ECMAScript specifications for all the details when converting stuff.

Categories

Resources