I've been meaning to write this up for a while, and now seems like as good a time as any.
Most people don't seem to know that the AND and OR operators in most programming languages have a useful feature built-in, which can be exploited for shorter code in a way most people wouldn't consider. Most people are used to using them in if
and while
and so on; this shows a good use of them outside of that context.
Say you have two variables, a and b, and you want to choose between them so that if a isn't false-y, it will use a, but otherwise use b. The obvious, but long-winded way to do this, is:
if (a) { a } else { b }
But OR usually has a nice feature built-in that does this for you — it doesn't just return "true" or "false" as most people think: it returns the first of its elements which is true-y. This means you can just do:
a or b
Once you're used to it, it doesn't make your code any less readable: you can think of it as "a if it's true, or b if it's not." The variables a and b can of course be any expression; it also extends nicely to cover more than two: a or b or c or d
will first try a, then b, then c, then d, and return the first true-y result of any kind.
The OR trick is nice, but AND also has a similar trick up its sleeve. Say you want to return b only if a is true-y. One way to do it is the obvious:
if (a) { b }
But you can also do:
a and b
and get the same result. This isn't normally useful, but if your language has if
as a statement rather than an expression, you can use it to good effect in arguments to function calls, passing a result, b, only if a is true and a null value otherwise. (You might also be able to use a ternary operator for this, such as (a ? b : null)
, but that requires explicitly stating a null value.) There's no easy mnemonic for this, but it can be useful. And you can treat AND as you normally would in its first operand: a and c and b
will return b only if a and c are true-y.