ELI5: Explain Like I'm 5

Dangling else

Okay, imagine you have two choices: A or B. Now, you want to do something based on your choices.

Let's say you are going for ice cream and you have two options, chocolate or vanilla. But you want it with a topping, sprinkles or caramel. Of course, you don't want to end up with only ice cream, so you start with "If I choose chocolate ice cream, I will have sprinkles, else I will have caramel."

Now what will happen if you forget to put the "else" and you say, "If I choose chocolate ice cream, I will have sprinkles."?

Well, then it becomes a dangling else, because it's not clear what happens if you choose vanilla. Do you get caramel or nothing at all?

Similarly, in coding, if we forget to add the "else" part after the first "if" statement, it leads to confusion, which may result in errors. The dangling else might lead to unexpected outcomes because the code might always execute the wrong block.

So, it's essential to follow the programming standard and avoid leaving "if" statements "hanging" without providing instructions for what to do in case it evaluates as "false."
Related topics others have asked about: