There's no "else if" in JS

Fabio Russo - May 20 '18 - - Dev Community

Grammar is not a joke...

Exactly, in Javascript's grammar there's no else if statement.

How many times have you used it before? Why It's still working?

We always code like this:


function wow(arg){

  if(arg === "dog"){
    return "LOVELY";
  }
  else if(arg === "cat"){
    return "CUTE";
  }
  else return "gimme an animal";
}

wow("cat");
//-> "CUTE"

Enter fullscreen mode Exit fullscreen mode

But what's really happening is this:


function wow(arg){

  if(arg === "dog"){
    return "LOVELY";
  }
  else {
    if(arg === "cat"){
        return "CUTE";
    }
    else return "gimme an animal";
  }
}

wow("cat");

Enter fullscreen mode Exit fullscreen mode

What's happening here?

Literally, we're using some implicit JS behavior about {} uses.

When we use the else if statement we're omitting the {} but Javascript It's still working because It does not requires the parentheses in that case, like in many other cases!

...so what?

I'm not writing this post, just because It's something really curious to know.

I'm writing this to make you think about all the good parts or right ways to code, that forces you to write code in a way, that sometimes It's not really the best way.

There's a lot to discuss about implicit and explicit declaration of stuff like: coercion, parentheses, semicolon...

But the true always stands in the middle!.

If you just follow some specific rules on how to... you're not understanding why those rules were written, and this else if should make you think about It.

How many time have you written code, because someone told you to do so but you were totally blind about It?

I bet, a lot.

I'm not saying that we should not care about ALL those rules, and that we should know ALL the JS documentation.

I'm just saying that right now, your duty is to write good code that can be understood by someone else and to go that way... some rules are ok, but you should know the why.

Because someone is good at code, It does not mean that you have to follow his golden rules.

What's implicit for him, maybe explicit for you and many other people.

If you don't have the same knowledge, about that specific argument (and It's not possible to have exactly the same level of know about It in every single part of the code) you've two options:

  1. Do what he's telling you to do... If It works.
  2. Go out and check the why

Always care about the good parts but first of all, always care about your knowledge and don't code just by rules.

Best-practices must be accepted by many people


think
. . . . . . . . . .
Terabox Video Player