JavaScript Conditionals: crazy math with boolean
Boolean Algebra can be fun
Jenny had a math quiz coming up, so she asks Billy to quiz her.
Billy is a nerd, and even better, he is a Computer Scientist.
Billy is in love with boolean, you know ones and zeros. So he has a brilliant idea.
So, Billy says to Jenny
Lets play a game called solve the puzzle.
If the result is true
you have to touch the spider.
Ok, said Jenny, let's do this, I am great at math...
Here is the puzzle, said Billy.
what is 7 less than 6, less than 5?
Jenny looks confused, so she said to Billy
I need a hint, do me a favor write it down.
so Billy wrote
7 < 6 < 5
Jenny thought long and hard about it, she looks at it, then says to herself.
well 7 is not less than 6, so that is false,
and 6 is not less than 5. so that is false
Ok, Jenny has the answer. She is terrified of spiders, there is no way she is going to touch that thing. She is confident
So she said to Billy, with a smile on her face,
The answer is false.
Billy started laughing.
Jenny said, why are you laughing,
Billy said “because you didn’t read the question properly”
give me that paper, let me draw some parentheses. you know order of operations right? Can you read it now that it has a pair of round brackets?
(7 < 6) < 5
Jenny looks at it, tries to evaluate it, then she said, ok I see
7 < 6 is false, so that becomes false < 5
So “false less than 5 ?”
Billy, that doesn’t make sense to me.
Are you trying to trick me Billy? is this math?
Yes it is, said Billy, think about it, ones and zeros, boolean.
what is “false” Jenny ?
zero (0)
what is “true” ?
one (1)
So, is false less than 5?
Jenny scratches her head for a while, thinking long and hard about it,
Well “false less than 5” is the same thing as saying “zero is less than 5”
console.log(false < 5 === 0 < 5) //↪ true
“Ok, I got it Billy”, Jenny said
The answer is true.
OMG, Billy, you tricked me, do I really have to touch that spider?
Hopefully it runs away when I try to touch it.
I am so scared!
Solved
console.log(7 < 6 < 5); //↪ truelet a = 7 < 6; //↪ falselet b = a < 5; //↪ true
console.log(b) //↪ true
Recap
In Boolean logic, a statement can have two values, true or false.
In a conditional context, JavaScript uses Type Conversion to coerce any value to a Boolean.
Sources
Graphics:
@moyarich (moyarich.com | codingstorytime.com)