Oleksiy's Blog

Return first!

04/22/2015

During AngularJS sourcecode investigation, I took a practice of place return {api} on the top of the revealing module, like here.

That construction can blow the mind of someone who has just come from other programming languages. JSLint does not like that as well. JSHint deals with "latedef": "nofunc" property.

But for those who know well JavaScript and understands how hoisting works, that should not make an issue.

WTF?!! What is this confusion for?

Well, there are some benefits.

Interface Segregation

First you see after opening a file is its interface. You don't need to scroll-down and dive into implementation.

var myModule = (function() {
  // interface first
  return {
    init: init
  };

  // implementation then
  function init (arguments) {
    // body...
  }
}());

State control

If you're writing a stateful module this way, you will need to declare your module state variables on the top, because any other expressions except function declarations won't ever execute. So that you know exactly what state you're working with from the beginning and defend yourself that nothing will brake your code by resetting variable between function declarations underneath:

var myModule = (function() {
  var stateVariable = true;
  return {
    init: init
  };

  function init (arguments) {
    // body...
  }
  // these expressions won't ever executed
  stateVariable = false;
  var x = 123;
}());

You may have experienced side effects of uncontrolled state. That practice can help you keep your instance state more controlled within a module.

Function expressions don't work.

I hate when functions are declared via var, so I see it's beneficial. That is more fragile, less readable and makes callstack be a set of Anonymous functions.

var myModule = (function() {
  var stateVariable = true;
  return {
    init: init // init is returned as undefined
  };

  var init = function (arguments) {
    // body...
  }
}());

Summary

So everything here is about codestyle. It is specific, so be ready for flying crap from your team when taking it into conventions :).