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..... } }
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.
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.
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.
Usually I have input-validation return right away. Imagine if you had a bunch of conditionals, you'd get a mess of nested if
s right away.
Generally once I get past input validation I avoid multiple returns, but for validation I return right away. Keeps it cleaner IMHO.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With