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.

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.

"The result is 4"

"The result is 16"

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 #
Contents +