Andre Figueiredo
Andre Figueiredo

Reputation: 13425

Local function declarations should be put before or after "return"

What are the pros and cons? Is there a consensus or good practice established for this case?
What says linters tools, code conventions and standard guides about that?

function before(){
  // declare variables

  function x(){
  }

  // do stuff

  return x();
}

function after(){
  // declare variables
  // do stuff

  return y();

  // ------------------------
  function y(){
  }
}

Another example:

var Person = function(name) {
  var person = {
    name: name,
    smile: smile,
    talk: talk
  };

  // here alongside function execution?
  function talk() {
  }

  return person;

  // or here, after return statement?
  function smile(){
  }
};

Upvotes: 1

Views: 1371

Answers (2)

brk
brk

Reputation: 50326

It is a matter of personal choice and both has got and sweet side.

In the later case it's useful when developer needs to read quickly how functions are invoked at the top of the source file, without the necessity to scroll down and read the details about function implementation.

A style close to the second one is followed when binding member in angular js. Here is a link for recommended style-guide on how angular js binding members up top

Upvotes: 3

George Kagan
George Kagan

Reputation: 6124

Since functions get hoisted up the scope, there's no real difference, only preference.
return's natural place is at the end, so why not have it there?

Upvotes: 1

Related Questions