I have always written my JavaScript blocks
var functionName = function() {
if (someCondition) {
// stuff
} else {
// stuff
}
};
but today I saw
var functionName = function() {
if (someCondition) {
// stuff
return;
}
// stuff
};
I like that the first example is more explicit in the logic. What are some reasons why you would or wouldn't want to do it the second way demonstrated?
Don't Overuse the “Try-Catch” However, one of the common mistakes developers make is to overuse exception handling. Sometimes we do it to keep the code look consistent across different files and methods. But, unfortunately, these would cause adverse effects both for application performance and error detection.
The control flow is the order in which the computer executes statements in a script. Code is run in order from the first line in the file to the last line, unless the computer runs across the (extremely frequent) structures that change the control flow, such as conditionals and loops.
As with many programming languages, the primary method of dealing with exceptions in JavaScript is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution.
The try...catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed.
Less indentation in case you got more then one someCondition
.
Imagine:
var functionName = function() {
if (someCondition) {
// stuff
} else {
// stuff
if (someConditionB) {
// stuff
} else {
// stuff
if (someConditionC) {
// stuff
} else {
// stuff
if (someConditionD) {
// stuff
} else {
// stuff
}
}
}
}
};
Which would be a lot more readable without all the elses:
var functionName = function() {
if (someCondition) {
// stuff
return;
}
if (someConditionB) {
// stuff
return;
}
if (someConditionC) {
// stuff
return;
}
if (someConditionD) {
// stuff
return;
}
// stuff
};
Many coding standards mandate that you shouldn't "early exit" from functions. It's a trade-off between readability, and "correctness" [*]
The early exit avoids the need for the subsequent code to be indented in an extra level. For example, IMHO it makes sense to have some error detection checks grouped together at the top of functions with an early exit on failure, with the meat of the function written as normal.
On the other hand, when reading code for debugging purposes it's easy to miss the early exit, and end up trying to find a bug in the wrong part of your code.
[*] those same code standards often eschew usage of break
and continue
. FWIW I think it's a symptom of over application of Djikstra's "GOTO considered harmful" mantra.
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