I am working on a project which requires some pretty intricate JavaScript processing. This includes a lot of nested if
-else
s in quite a few places. I have generally taken care to optimise JavaScript code as much as possible by reading the other tips on Stack Overflow, but I am wondering if the following two constructs would make any difference in terms of speed alone:
if(some_condition) { // process return ; } // Continue the else condition here
vs
if(some_condition) { // Process } else { // The 'else' condition... }
They are equally efficient, but B is usually considered to give better readability, especially when used to eliminate several nested conditions.
Here's the code: var isEven = function(number) { if (isEven % 2 === 0) { return true; } else { return false; } }; isEven(2);
To put it simply a continuation is a function which is used in place of a return statement. More formally: A continuation is a function which is called by another function. The last thing the other function does is call the continuation.
Definition and Usage. The return statement stops the execution of a function and returns a value. Read our JavaScript Tutorial to learn all you need to know about functions.
I always go with the first method. Easier to read, and less indentation. As far as execution speed, this will depend on the implementation, but I would expect them both to be identical.
In many languages, is a common practice to invert if
statements to reduce nesting or use preconditions.
And having less nesting in your code improves code readability and maintainability.
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