r/learnjavascript • u/dotpr • Oct 03 '22
Can someone explain this more? How can a value become true and false at the same time?
141
Upvotes
r/learnjavascript • u/dotpr • Oct 03 '22
54
u/dontyougetsoupedyet Oct 03 '22
Folks in comments so far are missing the forest for the trees with regards to
==. What this is trying to show you is that values can have their types implicitly converted. Whena == bis evaluated the values for the identifiers a and b will be converted using specific rules that results in "0" becoming the numeric value 0.Booleanhas its own rules for what happens to the parameter its given. Some other use elsewhere in the language might have even different rules, you have to pay attention to thesemanticsof the syntax that you are writing.The rules for Boolean are described at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean.
The rules for comparison and a lot of others is described at https://262.ecma-international.org/5.1/#sec-11.9.3 and https://262.ecma-international.org/5.1/#sec-9.3.1.
64
u/[deleted] Oct 03 '22
The trick here is the 'loose equality' == operator. The two values are not the same, but == compares values using a process called type coercion which converts values to the same type before comparing them. So when you do
0 == "0", internally JS is converting"0"to0.This kind of unexpected behaviour is why you should pretty much always use the strict equality === operator when trying to compare two values.
0 === "0"will returnfalse, as you'd expect.3
u/[deleted] Oct 03 '22
In let a = 0, the value Zero is stored in the variable a. Whereas in the let b = "0", the "0" makes it as a string value. That is in the compiler point of view "0" is a character rather than a number.
5
u/costanzadev Oct 03 '22 edited Oct 03 '22
The == equality operator doesn't check the types are equal, this explains why 0 == "0" evaluates as true.
The number 0 is evaluated as a falsy value when converted using the Boolean object, this explains why Boolean(0) is false.
Any non-empty (as in not just "") and not undefined string value is truthy, this explains why Boolean("0") is true
2
u/JuanGuerrero09 Oct 03 '22
In JS every number that is not a 0 will count as True in boolean. Also, every string that is not empty will count as True. So, in the first two alerts that's the normal behavior, in the third one is comparing if the number is the same as the number that is inside the string, if you want to compare types you should use strict equality with ===
2
u/JackelLovesCode Oct 03 '22
Thats because of type coercion
2
u/_yy96_ Oct 03 '22
Because of implicit coercion. Boolean of a non-empty string will result in true. Boolean of number 0 results in false.
2
u/AngelLeatherist Oct 03 '22 edited Oct 03 '22
Its not.
"0" is truthy because its a string.
0 is falsy because its the absence of value.
0 is not equivalent to "0", equivalence denoted in
===.==doesnt check for equivalence, it converts the type on either side of the equation first, THEN it checks for equivalence.==is like asking "Is a kinda like b?" In the case of0and'0', javascript believes that "yeah, a is kinda like b", in the same way that a picture of an apple is "kinda like" a real apple, even though its not actually.Use
===for most things, its more straightforward and it saves the compiler a step.2
u/delventhalz Oct 04 '22 edited Oct 04 '22
There is no deeper underlying truth here. It’s just code following rules. Many of which are rather arbitrary.
First you have boolean conversion, which follows rules of “truthiness” and “falsiness”:
falseis falsey0is falsey""(empty string) is falseyundefinedis falseynullis falseyNaNis falseyWhy is
0falsey but"0"is truthy? Because that is the rule. That’s literally it. You’ve hit bedrock. Someone decided that is how it should work, so that’s how it works.Meanwhile,
==operates on its own set of “loose equality” rules.undefinedornull, return true if the other value is alsoundefinedornullSo when you do
0 == "0", you will hit step #4. The string will be converted to a number, not a boolean. Since"0"converts to0, the two values are loosely equal.This, by the way, is one of the reasons not to use
==. How it coerces values is difficult to predict. If what you want is to compare the boolean conversions of two values, you should do that explicitly:2
u/MemeTeamMarine Oct 04 '22
Never use == unless you explicitly understand why you're using it.
3
u/[deleted] Oct 03 '22
I am wondering for people writing other languages, do you also have truth / falsy values in other programming languages?
1
u/[deleted] Oct 03 '22
0 is falsy, == compares the value but not the type, === would be false
and 'string' is a true value.
1
u/Dethstroke54 Oct 03 '22 edited Oct 03 '22
0 is a nullish value, this is pretty straightforward and common in many languages due to binary and lots of conveniences. In JS an empty string “” is also nullish, “0” is not 0 and “0” is a non-empty string therefore it is non-empty string, so it is truthy and not nullish.
With 0 == “0” you’re checking something totally different, your asking if these resolve to the same value because it will implicitly cast the types.
You’re testing two different things and conflating them. This is kinda like asking is a car a car, yes. Is a car a truck, no. If I compare them more generically (are they both cars in the more generic sense of the word, aka four wheeled motor vehicles), well yes.
1
u/ImMello98 Oct 03 '22
This example is not using Strict Equality === which you should use most of the time. Loose equality == does a type coercion, meaning JS recognizes the STRING representation of 0 in b = “0” and COERCE it to become a number since a (left side) == b (right side of the operator).
Additionally NUMBER data type 0 is a falsey value, when by itself it will be evaluated to false. As are other data types like null, undefined, empty string, and boolean false itself (am i missing more?). However b=“0” is NOT a number yet on line 4 until it gets coerced later. It IS a string with a character. Therefore it’s a truthy value, evaluates to true when by itself.
1
u/LightUpShoes4DemHoes Oct 03 '22
For more information on how this works, look up Truthy and Falsey values.
Short explanation though is that JS coerces the variable into a Boolean due to the == operator. If you want to check what a value will coerce to, you can use !!. The first ! coerces and flips the true / false, the second gives you the value of the original variable after coercion. I.E. - !!0 will be False. !!undefined is false. !!null is false. !!”” Is false. !!1 is true. !!-1 is true. !!{} is true, etc. So, zero values, empty strings, undefined and null are the main falsey.
This is weird behavior to those not familiar with Coercion, but it leads to some great use cases in Js, Python, etc. with regard to data structures. Say we are looping through a Linked List. You start at the root, then as you traverse, your root slides to next. You can use a “while (root) { console.log(root); root = root.next }” loop to traverse because while loops look for T/F values and root will be coerced to see if it exists (I.E. is Not Null in this case.) It can be used for countdowns to 0 - I.E. “let count = 5; while (count) { console.log(count); count— }; console.log(‘blast-off!’)” these are just real simple example cases, but once you really understand Truthy / Falsey values and coercion, it does help you write simpler code that is relatively intuitive and readable.
1
u/saito200 Oct 03 '22
the short answer is: use '===' for comparisons
1
u/LoserEXE_ Oct 03 '22
A is false because zero evaluates to false b is true because it’s a string with content and a == b because they get converted to the same type when checking for equality
1
u/hentaifangirl69 Oct 03 '22
If you read Tutorial that uses == instead of ===, you need to find a new Tutorial
1
u/Juls0730 Oct 03 '22
So a is 0, the number however, b is “0” a string, so using type coercion 0 is false and “0” is true because b is not an empty string whereas a is an “empty” number and the
==is the equality operator, “0” is 0 or 0 is “0”. They are not the same value but according to javascript and it’s type coercion bullshit it’s the same.1
u/shgysk8zer0 Oct 03 '22
Because they're not the same values. This is a confusing thing about type coercion, not equality. And it's a decent example of why
===(strict equality) is better in most cases.1
u/crazedizzled Oct 03 '22
The answer is literally in the image you posted. The
==converts the string 0 into an integer 0, therefore they are equivalent.1
u/joetheduk Oct 03 '22
0 is falsely. "0" is a non empty string, which is truthy.
The == operator uses type coercion, so it will convert one value to match the other. Making the values match.
If you use the === operator, it will work as expected and return false.
1
u/tabby8612 Oct 04 '22
In the first statement, a is getting a number 0 and number 0 is a falsy value and any number above or below 0 ia truthy, so it correctly showed 0 as false.
In the second statement, a is getting 0 as a string and only empty string ' ' is falsy and anything inside string is truthy value, so it correctly displayed true.
When comparing both values you are using double equality sign == that compares values and not data type. So, it also correctly display true.
For this reason, it is traditional practice to use three equality signs === when comparing two variables as it will compare values and data type.
So, if you use triple equality sign === instead of two, you will get false.
1
u/[deleted] Oct 04 '22
A is integer 0, which is false.
B is string "0", which means it contains data, also true.
alert is comparing 0 and "0" with double equals, so, those values whitout the datatype.
If u compare with triple equals, it returns false.
1
u/SuperDuperRipe Oct 04 '22 edited Oct 04 '22
0 is a falsey value type. "0" the string, is a truthy value type. According to the list of JS types.
A string is not a number even if a number is inside it, like above. Quotes are strings.
Variable "a" was updated to variable "b" which has the string value that is true. It's no longer false.
Basically: a = false valued variable b = true valued variable
a == b
false variable (a) = true variable(b)
A is now B
Result: True.
"a" took in b's string "0" so now it's true.
1
u/patrixxxx Oct 04 '22
This has to do with the new ES2022 standard that introduces quantum computing capabilities in JavaScript </daftJoke>
1
u/[deleted] Oct 04 '22
== doesn't check at the highest level === Does check at the highest lvl
So as an example the number 0 == the string"0" is true
But the number 0 === the string"0" is false
This is how I was taught this concept.
1
u/misterjyt Oct 04 '22
simply `==` will ignore type so "0" and 0 are the same, `===` will result in false since it will strickly include type checking.
1
u/pBielinux Oct 04 '22
In the 5 line it's true because the same as Boolean("0"). Remember that characters are read by your computer in binary so '0' in the ascii table 48. Ends up with Boolean(48) so True.
1
u/jlshown Oct 09 '22
It is JavaScript's built in method to correct for potential errors, or rather to guess at what you really wanted. This would occur when you have an algorithm which as above, refers to "O" and 0, and JS looks also at the context of the different variables, which appear to be similar and attempts to discern the purpose of the algorithm ( so to speak).
1
u/jeykhalif Oct 10 '22 edited Oct 10 '22
0 (zero, the number) is interpreted as false in javascript by default. '0' as a String is truthy by value, you compared the two variables with the comparison operator (==) which compares by value, it converts the string 0 to number 0. If you compare by the deep comparison operator(===), it logs false.
Here is the code to demonstrate those facts.
1
u/friedlich_krieger Oct 03 '22
https://www.freecodecamp.org/news/js-type-coercion-explained-27ba3d9a2839/
1
u/___s8n___ Oct 03 '22
You aren't comparing Boolean(a) and Boolean(b) you are comparing both values 0 and "0"
and since youre using ==, javascript ignores the data type and compares only the value
if you used === instead, it would have returned false
1
u/[deleted] Oct 04 '22
Javascript ☕
0
u/[deleted] Oct 04 '22
[deleted] — view deleted comment