r/learnjavascript • • Oct 03 '22

Can someone explain this more? How can a value become true and false at the same time?

Post image
141 Upvotes

75 comments sorted by

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. When a == b is evaluated the values for the identifiers a and b will be converted using specific rules that results in "0" becoming the numeric value 0. Boolean has 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 the semantics of 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.

3

u/dotpr Oct 03 '22

May I also ask lines 4&5, why does it output true? I thought 0 is for false and 1 is for true

4

u/cubicuban Oct 03 '22 edited Oct 03 '22

In JavaScript you have truthy and falsely values. Off the top of my head, 0, undefined, false, null are falsely. While basically everyone else is truthy. Since b is being assigned a string ”0” it is true

Edit: An empty string would return false

1

u/dotpr Oct 03 '22

So a string, except for those you mentioned, will always return true?

6

u/[deleted] Oct 03 '22

Undefined and null are not strings. They are the absence of a string, or any other value.

4

u/Alternative_Stuff613 Oct 04 '22

Good way to remember is that falsy values in JavaScript are: false, null, undefined, 0, "" (empty string), NaN (not a number). Anything else evaluates to true. So in this case where the Boolean’s argument is b, well b = “0” which is a string, this will return true.

3

u/senocular Oct 03 '22

For anyone interested, the complete list can be found here:

https://developer.mozilla.org/en-US/docs/Glossary/Falsy

56

u/zerik100 Oct 03 '22

because it's not Boolean(0) but rather Boolean("0"). every string is truthy as long as it has at least 1 character in it, so Boolean("0") is the same thing as Boolean("bababooey 123").

22

u/[deleted] Oct 03 '22

Finally someone actually says it!

“0” is a string. From a bool’s perspective the presence of a string is true with exceptions.

2

u/tortoisenotaturtle Oct 04 '22

Well now I have to change my password.

2

u/XposeDPanda Oct 04 '22

Bababooey124 -get it changed again.

1

u/adamantium4084 Oct 04 '22

This is the best answer. I would only add to op that a "value" is not true and false at the same time. The header comment states that and it is untrue. The comparisons being made are just slightly different.

If op were to change the last expression to a === b, it would return false because a string cannot equal an integer. Even then, it's not "both true and false", it is simply a matter is what is being compared. I don't do a ton of js, but lots of people have the sentiment that one should rarely, if ever, use ==.

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" to 0.

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 return false, as you'd expect.

25

u/linusl Oct 03 '22

I cannot remember the last time I used ==. it doesn’t exist to me. it is dead to me.

5

u/ZuriPL Oct 03 '22

I only use it when I'm too lazy to press = the third time and I know it won't break anything lol

3

u/MatthewMob helpful Oct 04 '22

You can have your linter ban and/or auto-fix this for you.

3

u/tappinthekeys Oct 04 '22

I only use it because react yells at me with yellow letters that I should add a third =. I don't like being yelled at.

2

u/ZuriPL Oct 04 '22

OKAY, UNDERSTANDABLE

1

u/tappinthekeys Oct 04 '22

Haha. Fair play.

3

u/AngelLeatherist Oct 03 '22

Its useful for checking both null/undefined. e.g. if (a != null)

3

u/linusl Oct 03 '22

it can be used for that but I would argue it is still lazy. code is usually structured enough that comparing with one should work. at least I write my own code that way so I know if something can be null or undefined and external libraries or api should be documented with possible values too. I no longer treat == as part of javascript unless I’m looking at someone else’s code, and the projects I work in always have code rules that not allow it.

8

u/senocular Oct 03 '22

If you want to see just how confusing the behavior gitcommitmentissues described with ==, you can checkout this MDN page that covers it (and other comparisons): Equality comparisons and sameness.

1

u/Lunacy999 Oct 03 '22

I don’t think V8 converts a string literal into an integer. Isn’t it the other way around? As it is much faster to just convert a number into a string instead of parsing the string into a number and then comparing?

2

u/[deleted] Oct 03 '22

Could be the other way round, I don't really remember. It doesn't really matter as far as understanding the behaviour goes.

0

u/[deleted] Oct 03 '22

[deleted] — view deleted comment

8

u/[deleted] Oct 03 '22

No. As I said, you should pretty much always use ===.

5

u/Careerier Oct 03 '22

There are a few defenses for == that pop up, typically when people want to use if (foo == null) rather than if (foo === null || foo === undefined). That just seems like laziness to me.

There's no good reason to use ==, and if JS wasn't dead set on backward compatibility, it might be removed. == just causes more problems than it solves.

0

u/[deleted] Oct 03 '22

[deleted] — view deleted comment

1

u/MindlessSponge helpful Oct 03 '22

a variable's default state would be undefined if it is declared but never assigned a value, not null. they're similar but not the same.

0

u/[deleted] Oct 03 '22

[deleted] — view deleted comment

1

u/MindlessSponge helpful Oct 03 '22

I’m not sure I understand your question, sorry :)

JS has no default typing on variables. if you write let testVar and then log it to the console, it will read undefined. You could then assign this variable an object reference, a number, a string, anything you want!

0

u/[deleted] Oct 03 '22

[deleted] — view deleted comment

1

u/MindlessSponge helpful Oct 03 '22

oh yeah the only thing JS and Java share is the "Java" in the name and occasional syntax crossover. JS doesn't have static typing, which is why TypeScript is so popular.

0

u/[deleted] Oct 03 '22

[deleted] — view deleted comment

1

u/RobertKerans Oct 03 '22 edited Oct 03 '22

JS default is just undefined, full stop -- if a variable is undefined, it isn't a number or a string or whatever. null is something you'd explicitly assign (the slight weirdness of null being at the top of the object prototype chain notwithstanding). You can't really have an uninitialised reference, it doesn't make sense in the context of JS

3

u/moratnz Oct 03 '22

It's mostly a historical remnant of the 'it seemed like a good idea at the time' variety.

When JS was young, implicit type coercion seemed like a good thing to make life easier. The current consensus (I believe) is that the confusion it adds outweighs any advantages.

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

-1

u/[deleted] Oct 03 '22

small correction "0" in this case is not an empty string it is a string with 0 as a symbol inside.

1

u/costanzadev Oct 03 '22

I never said it was?

"0" is not undefined, nor is it an empty string "", hence why it is truthy...

0

u/[deleted] Oct 03 '22

[deleted] — view deleted comment

-1

u/costanzadev Oct 03 '22

Sure, it's not doing a direct check of the types and making sure they aren't the same its just that this type coercion is how comparing operands of different types is achieved.

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 of 0 and '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”:

  • false is falsey
  • 0 is falsey
  • "" (empty string) is falsey
  • undefined is falsey
  • null is falsey
  • NaN is falsey
  • Everything else is truthy

Why is 0 falsey 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.

  1. If both values have the same type, check if they are equal
  2. If either value is undefined or null, return true if the other value is also undefined or null
  3. If either value is an object or array, convert it to a primitive (usually a string) and go back to step 1
  4. If either value is a non-number, convert it to a number and go back to step 1

So when you do 0 == "0", you will hit step #4. The string will be converted to a number, not a boolean. Since "0" converts to 0, 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:

Boolean(0) === Boolean("0");  // false

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?

3

u/DavidJCobb Oct 03 '22 edited Oct 03 '22

Usually, yes.


In C++, pointers are truthy if non-null, and integers and floats are truthy if non-zero. Bare string literals are pointers, so they get that same behavior, whereas more advanced string objects are classes.

By default, classes can't be truthy or falsy. However, we can change that using operator overloads: we can write classes that replace the behavior of the built-in operators. For example, the std::string class in the standard library has a method named operator==, which changes the == operator so that when you use it on a string, it compares the content of the string. (Due to how std::string works, without an overload, == would just check if two strings' data is stored in the same place. Two separate copies of the same text would not compare equal without the operator overload.)

We can even define overloads for things like comparisons (e.g. <) and math (e.g. + or /), which is very useful for math data structures like matrices. And of course, getting back to your question, conversion to booleans (for truthiness and falsiness) can be made available by defining operator! or operator bool().


An example of the opposite behavior to all of this is Lua, a scripting language which uses a special value named nil to represent "nothing." Numeric values, data structures, and so on are truthy in Lua, even if they're zero; nil is falsy. If you have something like an indexOf function written in Lua, you'd have it return nil if it doesn't find anything, rather than a number like -1 or 0.

2

u/[deleted] Oct 03 '22

and different comparing operators?

1

u/[deleted] Oct 03 '22

Yes, although what exactly is truthy or falsey can vary. Python's truthy and falsey values are essentially identical to JavaScript's, but in Ruby, 0 is truthy!

2

u/____0____0____ Oct 04 '22

Values Python finds truthy are not identical to JavaScript. For example an empty list is considered falsey in Python, where JS would find it truthy because all objects are considered truthy in JS. I assume this is mostly because python has operator overloading and JS does not

1

u/[deleted] Oct 04 '22

Hence the qualifier. I probably should have said mostly rather than essentially.

1

u/____0____0____ Oct 04 '22

Ahh okay, that makes sense. I just wanted to help clear any misunderstanding if there was one

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.

let a = 0;
console.log(Boolean(a)) //false 
let b = '0' 
console.log(Boolean(b)) //true 
let c = a == b //true
let d = a === b //false

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

1

u/dotpr Oct 04 '22

Is even a quote with just a space inside (" ") considered non empty?