Skip to content

Instantly share code, notes, and snippets.

@allenwlee
Forked from devinrhode2/fn-naming.markdown
Last active December 17, 2015 19:29
Show Gist options
  • Save allenwlee/5660512 to your computer and use it in GitHub Desktop.
Save allenwlee/5660512 to your computer and use it in GitHub Desktop.

An advanced function naming style

Everywhere possible, this is the preferred style, if you understand all the quirks to it. There aren't too many.

function foo() {

}

With this, you get function names in the fewest possible characters, there's only one caveat:

if (thing) {
  function foo() {
  }
} else {
  function foo() {
  }
}

The browser tries to hoist the definition to the top, but there's two declarations!. What should the browser do? This is invalid javascript.

Function declaration syntax are only valid at the top indentation of a function. You can't (shouldn't) use it inside if, while, for, etc control blocks.

(function racerJS(){
  function valid() {
    ...
    function alsoValid() {
      if (something) {
        function NOT_VALID() {
          
        }
        var butImValid = function butImValidF() {
          
        };
      }
    }
  }
})()

If you are not at the top indentation of a function block, or at the top of a <script> you should use this syntax:

var foo = function fooF() {
};

Notice the function name is fooF the F is important for avoiding errors in oldIE, it's easy and you should do it so you don't have headaches getting your JS to run in IE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment