I came across this code in Mithril.js
:
finish(state == 1 && 3)
To my (Java/C programmer's) eyes it looks like it should always invoke finish(true)
if state
is 1
and finish(false)
if state
is not 1
. But it actually seems to do finish(3)
for the former and finish(false)
for the latter.
What is the logic behind this?
Is this idiomatic in JavaScript, or is it a bad idea? To me it's horribly obscure.
You can interpret the operators ||
and &&
like this:
A || B
→ A ? A : B
A && B
→ A ? B : A
But without evaluating A
twice.
It is a characteristic of JavaScript, && and || operators always return the last value it evaluated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With