Search code examples
javascriptfunctionhoisting

Using a function in another function before that first function is defined


When writing an API, I tend to like putting the functions in a top-down order, with the most exposed functions at the top, and the helper functions at the bottom. However, when defining functions with var rather than the magic function delcaration, a function cannot be used before it's defined. So what about if we have an object called $company and we're defining its methods. Can I safely order my JS in this fashion?

var $company = {};

$company.foo = function(x) {
    $company.bar(x*x); // used in definition, but not called directly - ok?
};

// $company.bar(6) // this would produce an error

$company.bar = function(x) {
    alert(x);
};

It seems to work in my current version of Firefox, but I'd like to know if it's defined behavior. Are there any versions of IE where this breaks?


Solution

  • Yes you can.

    Functions are only defined, not executed.

    The JS engine executes each line of your file :

    var $company = {};
    $company.foo = ...;
    $company.bar = ...;
    

    And later, at $company.foo execution, $company.bar is defined!