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.....
}
}
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.