Search code examples
javascriptconventions

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(){
  }
};

Solution

  • 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