Is there any point to the else after an if?<p>Why do we need else?<p>Can’t we chuck it away?<p>Does else serve a purpose?<p>NOTE: I’m not talking ternaries. Ternaries are super useful.
Technically, we probably could, but would often need workarounds for code which changes the initial condition such as,<p><pre><code> i = 0
if i <= 0:
i += 1
else:
i -= 1
</code></pre>
You could of course solve this in various ways, for example something like:<p><pre><code> condition = i <= 0
if condition:
i += 1
if not condition:
i -= 1
</code></pre>
But i don't find that to read as well as an else block. Also restating longer conditions which we don't change in the then-block to mimic an else with an if seems like a waste of spacetime.
All syntax is about what's convenient for people to structure their world. If it weren't, we'd all just be writing machine code.<p>The word "else" exists in every human language, implying that people have a thought pattern for "if this then that, otherwise the other thing". Structuring code is hard enough, so taking cues from human language is a good heuristic.<p>If/else is side-effecty. Ternaries are the equivalent in a functional world. Some code is very natural in a functional style, but statefulness is another natural way for people to work. Every time you write intermediate results on scratch paper, you're doing stateful thinking. Every time you make a decision and take an action that can't be undone, that's stateful thinking.<p>There are some purely side-effect-free languages, but many developers find them unnatural. At the very least it requires a substantial revamping to think about databases and UIs in a purely stateless way. And if you're working in a stateful language, if/else is a natural way to express some actions.<p>People are increasingly pushing toward functional programming, and the more you do that, the fewer else statements you write. In fact, the fewer if statements you write as well. If statements are kind of a code smell -- and in fact, ifs without elses are also a code smell. They hint at asymmetry, and there's a hidden "don't do anything" that should make you wonder if you should have done something.