-2

we're implementing a new Javascript framework at work (http://app.igaro.com) where the author has inlined many of his return statements. Take https://github.com/igaro/app/blob/master/compile/js/core.language.js as an example.

My boss has told me not to do follow this approach, but can give no reason for doing so, other than he prefers the look of expanded code. Which is considered best practice?

if (dosomething) return 30;
if (trythis) return 20;
return false;

-v-

if (dosomething) {
 return 30;
} else if (trythis) {
 return 20;
} else {
 return false;
}
  • 1
    Using multiple return statements can sometimes make functions hard to read, see this post for more info: http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement – Alfie Aug 30 '14 at 04:27
  • I wonder what your boss thinks of JSON one-liners... – Jeff Clayton Aug 30 '14 at 04:42

3 Answers3

2

There are three separate issues here:

  1. Should you always put the body of an if statement in curly brackets?

  2. Should you return from the middle of a function?

  3. Do you need to use else after an if which returns?

For (1), there is a strong consensus I would say for "yes", and jslint/hint would enforce that.

For (2), my personal opinion is that if you want to get out of a function quickly you should do this. This technique can also reduce excessive nesting.

For (3), it seems pointless.

1

This comes down to coding standards that you agree on as a team. There is no best practice beyond that.

TGH
  • 38,769
  • 12
  • 102
  • 135
1

Well the second one is really the one which you should follow. Omitting brackets can lead to confusions.

For example if the code is indented like this:

if(condition)
  var three = 1 + 2;
  return three;

One might expect it to be:

if(condition) {
   var three = 1 + 2;
   return three;
}

when instead it compiles to this:

if(condition){
   var three = 1 +2;
}
return three; // Error!

Douglas Crockford has said in his book Javascript: The Good Parts

Experience shows that this form is more resilient.

Now it is up to you to whether follow on of the finest javascript programmers' words or not.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • Visually this is a great point. Most of the edits I do first require me to space out others' code in order to make it so I can make sense of it first. – Jeff Clayton Aug 30 '14 at 04:37