0

I'm reading "Structure and Interpretation of Computer Programs: JavaScript Edition" (2022) by Abelson, Sussman et al. On page 64, the book talks about the "logical composition operations" (logical AND, logical OR):

  • expression1 && expression2

This operation expresses logical conjunction, meaning roughly the same as the English word and. This syntactic form is syntactic sugar for expression1 ? expression2 : false;

  • expression1 || expression2

This operation expresses logical disjunction, meaning roughly the same as the English word or. This syntactic form is syntactic sugar for expression1 ? true : expression2.

I don't understand how expression1 ? expression2 : false could be the same thing as expression1 && expression2.

In the first case, we just evaluate whether expression1 is truthy. In the second case, we evaluate whether both expression1 and expression2 are truthy. So why are they the same thing? I hope you can enlighten me? :) Thanks a lot!

Julia
  • 21
  • 2
  • 1
    The text is wrong. You might say it's *similar* in order to illustrate what happens but it's most definitely not the same. Consder `0 && 1` is not the same result as `0 ? 1 : false`. The AND will produce `0` while the conditional statement will produce `false`. – VLAZ Oct 13 '22 at 18:30
  • You could say that `expression1 && expression2` is the same as `expression1 ? expression2 : expression1` which will be more correct but AND is not really syntactic sugar for it. The two are different `console.log("hello") ? "not reached" : console.log("hello")` is going to log *twice* while `console.log("hello") && "not reached"` would only log *once*. – VLAZ Oct 13 '22 at 18:33

1 Answers1

0

That's how the ternary (?) operator works, basically x = a ? b : c translates to x is b if a is true and c otherwise.

In the case of &&, we fist check expression1, if it's true, the truthiness of the whole thing depends on expression2 (which could be true or false), otherwise it's false

Abdellah Hariti
  • 657
  • 4
  • 8