Functions that return a function

Assigning a variable to a function (without the parenthesis) copies the reference to the function. Putting the parenthesis at the end of a function name, calls the function, returning the functions return value.

Demo

function a() {
  alert('A');
}
//alerts 'A', returns undefined

function b() {
  alert('B');
  return a;
}
//alerts 'B', returns function a

function c() {
  alert('C');
  return a();
}
//alerts 'C', alerts 'A', returns undefined

alert("Function 'a' returns " + a());
alert("Function 'b' returns " + b());
alert("Function 'c' returns " + c());

In your example, you are also defining functions within a function. Such as:

function d() {
  function e() {
    alert('E');
  }
  return e;
}
d()();
//alerts 'E'

The function is still callable. It still exists. This is used in JavaScript all the time. Functions can be passed around just like other values. Consider the following:

function counter() {
  var count = 0;
  return function() {
    alert(count++);
  }
}
var count = counter();
count();
count();
count();

The function count can keep the variables that were defined outside of it. This is called a closure. It’s also used a lot in JavaScript.

Leave a Comment