Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'return' instead of 'else' in JavaScript

I am working on a project which requires some pretty intricate JavaScript processing. This includes a lot of nested if-elses 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... } 
like image 359
jeffreyveon Avatar asked Nov 30 '09 16:11

jeffreyveon


People also ask

Which is better if else or if return?

They are equally efficient, but B is usually considered to give better readability, especially when used to eliminate several nested conditions.

Can I use return in if else in JavaScript?

Here's the code: var isEven = function(number) { if (isEven % 2 === 0) { return true; } else { return false; } }; isEven(2);

What can I use instead of return in JavaScript?

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.

Why do we use return in JavaScript?

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.


2 Answers

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.

like image 193
Josh Stodola Avatar answered Oct 04 '22 18:10

Josh Stodola


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.

like image 29
Christian C. Salvadó Avatar answered Oct 04 '22 16:10

Christian C. Salvadó