Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `(state == 1 && 3)` make sense? [duplicate]

Tags:

javascript

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.

like image 557
Lawrence Dol Avatar asked Sep 24 '14 19:09

Lawrence Dol


2 Answers

You can interpret the operators || and && like this:

    A || B
→   A ? A : B

    A && B
→   A ? B : A

But without evaluating A twice.

like image 78
kay Avatar answered Nov 06 '22 11:11

kay


It is a characteristic of JavaScript, && and || operators always return the last value it evaluated.

like image 9
Lochemage Avatar answered Nov 06 '22 11:11

Lochemage