DEV Community

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

Collapse
 
dguhl profile image
D. Guhl

The second code block is wrong, if you would like to show all the brackets.

This is the corrected code block:

function wow(arg){

  if (arg === "dog") {
    return "LOVELY";
  }

  else {

    if (arg === "cat"){
        return "CUTE";
    } 

    else {
      return ("gimme an animal");
    }
  }
}

The weird spacing is for demonstration: else is a keyword, working in pair with if. The reason why it's not noted like this is obvious: the else-blocks stack up a hierarchy, so that multiple else-if conditionals would add indentation and make the code unreadable with each additional condition. else-if is a construction to make such stacks more readable by taking away the need for stacking.

I myself recommend to hold brevity over the subtleties and nuances of syntax:

function wow(arg) {

  if(arg === "dog")
    return "LOVELY";

  if(arg === "cat")
    return "CUTE";

  return "gimme an animal";
}

Of course, this code would be harder to mutate in a patch. When the first condition would not return a string but alter the variable arg to "cat", the second condition would match and execute its code, while that would not happen when that condition would be else-enclosured. And eventually, the last line only works as the default case because the former conditionals end with their respective return themselves.

But that's why you got to think when you code.