DEV Community

Discussion on: If/else or just if?

Collapse
 
nektro profile image
Meghan (she/her)

The second one. Every time. For the early returns reason mentioned earlier. Since you're doing a return, the else is an anti-pattern.

Also this thread terrifies me for all the code that exists out there and solidifies everything about xkcd.com/2030/

Collapse
 
simbo1905 profile image
Simon Massey • Edited

Totally! "else" at the end of an if/else chain is a trap awaiting someone changing the input then making a mistake in the if/else such that the new input falls into the old else that does the wrong thing. Scala has "match" and the compiler gives an error if you don't match everything that can come in. Putting in a wildcard match at the end, which is equivalent of a last 'else' in JS, reads as "okay I don't recognise this input so I am going to ignore it". That screams anti-pattern as being both inefficient and inexact.