Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to wrap code into an 'IF' statement, or is it better to 'short circuit' the function and return? [closed]

I'm doing some coding in JavaScript, and I am having a lot of instances where I have to check some stuff before I proceed. I got into the habit of returning early in the function, but I'm not sure if I am doing this right. I am not sure if it have an impact on the complexity of my code as it grows.

I want to know from more experienced JavaScript coders, what is a better general practice out of the following two examples. Or is it irrelevant, and they are both OK ways of writing this particular IF block?

1) Returning Early or "Short Circuit" as I call it (Guard Clause).

ServeAlcohol = function(age) {      if(age < 19)          return;        //...Code here for serving alcohol..... } 

..Or...

2) Wrap code into an IF statement.

ServeAlcohol = function(age) {      if(age >= 19)      {           //...Code here for serving alcohol.....      } } 
like image 331
7wp Avatar asked Jan 12 '10 20:01

7wp


People also ask

What is better than an if statement?

A switch statement is usually more efficient than a set of nested ifs. Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing.

Why would someone want to use an IF statement while coding?

An if statement lets your program know whether or not it should execute a block of code. Comparison-based branching is a core component of programming. The concept of an if-else or switch block exists in almost every programming language.

Should you avoid if statements?

There is nothing wrong with using if-statements, but avoiding them can sometimes make the code a bit more readable to humans. This is definitely not a general rule as sometimes avoiding if-statements will make the code a lot less readable. You be the judge. Avoiding if-statements is not just about readability.


2 Answers

Usually I have input-validation return right away. Imagine if you had a bunch of conditionals, you'd get a mess of nested ifs right away.

Generally once I get past input validation I avoid multiple returns, but for validation I return right away. Keeps it cleaner IMHO.

like image 151
Parrots Avatar answered Sep 21 '22 18:09

Parrots


I prefer the first one, because it's a guard condition and you exit directly. But I don't think there is performance issues with either, just that it's your preference... Both will return execution directly...

like image 34
Brian Mains Avatar answered Sep 23 '22 18:09

Brian Mains