DEV Community

Discussion on: There's no "else if" in JS

Collapse
 
kodikos profile image
Jodi Winters

I'm not a compiler guru or have scoured the V8 code, but for languages that support this, the relevant BNF typically goes something like:
if-stmt ::= if <condition> <stmt> [else <stmt>] [;]
stmt ::= <expr> || <expr-block>

I.e. it's not an implicit set of brackets, it's one statement or a statement block.
If you're wondering why we do these things as rote, it's largely fashion. This is the fashionable way to write code at the moment. Many codebases are time capsules for the standards of the time, which is why everyone wants to rewrite them every 5 years! In only the last month or so, suddenly arg => arg is out of fashion (now has to be (arg) => arg)! In fact, seniors would most likely say your example should be a switch, but that's literally a dirty word these days (I had go way down the comments to find someone suggest it!), even though it's meant for exactly that situation. The fact you did this example in a small function and did returns is a relatively new phenomena.
The reasons for being overly syntactical were quite sane at the time. For example, the reason why we used to explicitly put brackets round every block in an if statement was because:

  • it was less prone to people forgetting that you needed them when you wanted multiple statements in the true/false statement
  • It was a less sophisticated development environment that could hardly do syntax highlighting let alone auto-linting and auto-indenting
  • Developers very much had coding styles, you didn't need to check the git log, not that git was around at the time
  • It was linted by humans and the consistency improved scanning speed
  • Where you threw debug statements into those condition blocks so regularly it helped if they were already there
  • It improved code reviews because your diff didn't alter lines above and below your commit with adding brackets when it became a statement block (surprised that one's not still valid, airbnb :D )
  • It was when you faced functions that were several hundred lines of code, and most if/else statements had many statements in them!

I don't think it's necessary for everyone to know these sorts of reasons why they're spared the extra syntax. But without going through the pain, we wouldn't know what were the good bits. But.. just maybe... you might have some more sympathy for the senior devs out there! :D