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

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


In JavaScript, the && operator doesn't force the result to a boolean. It's instead similar to:

var _temp = state == 1;
finish(_temp ? 3 : _temp);

Testing the truthiness of the left side, then returning either the right when truthy or the left otherwise.


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

    A || B
→   A ? A : B

    A && B
→   A ? B : A

But without evaluating A twice.

Tags:

Javascript