Inner (Private) Functions

As a function is just like any other value, you can define a function inside another function.

function a(param) {
    function b(theinput) {
        return theinput * 2;
    };
    return 'The result is ' + b(param);
};

Using the function literal notation, this can also be written as below.

snippet
var a = function(param) {
    var b = function(theinput) {
        return theinput * 2;
    };
    return 'The result is ' + b(param);
};

When you call the global function a(), it will internally call the local function b(). Since b() is local, it's not accessible outside a(), so we can say it's a private function.

a(2);
"The result is 4"

a(8);
"The result is 16"

b(2);
b is not defined

The benefit of using private functions are as follows:

  • You keep the global namespace clean (smaller chance of naming collisions).
  • Privacy—you expose only the functions you decide to the "outside world".
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +