JavaScript Best Practices: Functions

  • Function expressions:
    // anonymous function as event handler
    $el.on('click', function () {
      return true;
    });
    
    // optional name to aid debugging with stack traces
    $el.on('click', function elClick() {
      return true;
    });
    
    // anonymous function as method
    MyObject.prototype.isTrue = function () {
      return true;
    };
    
    // immediately-invoked function expression (IIFE)
    (function () {
      console.log('Welcome to the Internet. Please follow me.');
    })();
    
  • Function declarations:
    // use a named declaration when appropriate mainly
    // for internal helper logic and organization
    function namedFunction() {
        return true;
    }
    
  • Never declare a function in a non-function block (if, while, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears.

  • Note: ECMA-262 defines a block as a list of statements. A function declaration is not a statement. Read ECMA-262’s note on this issue.

    // bad
    if (currentUser) {
      function test() {
        console.log('Nope.');
      }
    }
    
    // good
    var test;
    if (currentUser) {
      test = function test() {
        console.log('Yup.');
      };
    }
    
  • Never name a parameter arguments. This will take precedence over the arguments object that is given to every function scope.
    // bad
    function nope(name, options, arguments) {
      // ...stuff...
    }
    
    // good
    function yup(name, options, args) {
      // ...stuff...
    }
    
 

austinvernsonger