&& and || operators as control flow

Try this:

> var a = 'b' || 'c';
> a;
< "b"

Now:

> var x = 'y' && 'z';
> x;
< "z"

Aha! So the && and || operators, in the context of the example above, can be more generally thought of, not so much "logical AND" or "logical OR", but rather control flow operators.

||, in the situation above, will take the first value that evaluates as truthy unless all evaluate as falsey. In more "conventional" terms, we might map that as:

var a;
if ('b') {
  a = 'b';
} else if ('c') {
  a = 'c';
}

Whereas &&, in a similar situation, will take the last value that evaluates as truthy, unless one evaluates as falsey. Here we might consider that, in terms of the evaluation logic, as somewhat similar to:

var x;
if ('y') {
  x = 'y';
}
if ('z') {
  x = 'z';
}

It is important to note that all values in the examples above, are truthy, as they are all non-empty strings. Of course, evaluating inherently truthy expressions in conditionals does not really carry a lot of meaning, the examples are to illustrate how the control flow is working.

Here is perhaps a more tangible example from a render method.

function render() {
  return (
    <div>
      {user.isAuthenticated &&
        user.firstName &&
        <span>Welcome, {user.firstName}!</span>}
      {user.isAuthenticated || <a>Log in</a>}
    </div>
  );
}

For me, this type of linear flow through a chain of expressions makes it easier to see where the program is headed. It is also worth noting that this kind of rhythm helps to reduce our mental picture of the code into buckets of truthiness and falsiness. There are more general ways of conceptualizing the application flow in terms of these two values. That is another very large topic though, which I can hopefully cover more carefully at a later date.


Sources:

  1. The JavaScript REPL