JavaScript: Putting the fun into functions

When Brendan Eich designed JavaScript and it’s function-model in the 90s, he was heavily influenced by the functional language Scheme. Just like Scheme JavaScript provides first-class and lambda functions aswell as closures. These mechanisms give functions in JavaScript a lot of power.

PFC Function

Most modern, wide spread programming languages draw a strict line between data and procedure. Functions are something very distinct in regard to variables and they behave very differently. E.g. you may not be able to reassign them or they cannot have any properties or other members. JavaScript is different though. In JavaScript functions are first-class objects – that is, objects just like any other object. As first-class objects functions can be assigned to variables, they can be passed as parameters and they may even have members of their own. You can use them in any way you could use any other object. But before we get into more detail about this, I will first introduce you to a JavaScript function:

  function f(parameter) {
    return parameter;
  }

This is a very simple JavaScript function. To be more precise, it’s a function statement. JavaScript knows two distinct notations for functions, which look very similar, but really do very different things: function statements and function expressions. For now the function statement will do. We will learn more about function expressions and their differences later.

As first-class objects functions can be assigned to variables, can be passed as parameters, be assigned as members to objects and even returned from other functions:

function f(p) {
  return p;
}
var g = f; // assign the function to a variable
g(0) === f(0); // true, both return the same value
g === f; // true, both actually are the same function
 
var o = {
  m: f // assign f as the member m of the object o
};
o.m(0) === f(0); // true, again both return the same value
o.m === f; // true, since both are again the same function
 
function condCall(cond, f, p) {
  if (cond) {
    return f(p); // the parameter f is treated as a function 
                 // and p is passed as argument
  } else {
    return f; // the parameter f is treated as a value
  } 
}
 
condCall(true, f, 0) === f(0); // true, since condCall will 
                               // call f providing 0 as an argument
condCall(false, f) === f; // true, since condCall will return 
                          // f as a value
condCall(false, f)(0) === f(0); // true, the returned value f will 
                                // be invoked immediatly

JavaScript functions can be handled like any other object. The only difference is, that functions can be invoked and do not inherit from Object.prototype directly, but from Function.prototype, which itself then inherits from Object.prototype though.

Making a statement. Or expressing yourself.

JavaScript knows two distinct ways to define a function. The first is the already shown function statement. A function statement always begins with the function keyword and is followed by a mandatory function identifier, an optional parameter list and an mandatory function body. The function’s identifier will be a valid variable identifier in the context where the function was defined. It should be noted that a function statement is what it’s name suggests: a statement. Just like a condition or a loop, a function statement itself does not return any value and thus works very similar to how function definitions work in other programming languages.

The other construct in JavaScript for defining a function is the function expression. The function expression is where functions get interesting. A function expression consists of the function keyword, an optional identifier, an optional parameter list and a mandatory function body. A function expression may occur wherever any other expression may occur. The optional identifier will only be valid inside the function body, if provided, but not in the context of the expression. Such a function expression is called a named function expression. Just as any other expression, function expressions also return a value. The value returned by the function expression is the function, or more precise a new function object that will execute the function body when invoked. To be able to invoke this function at a later point, you will need to store the function object in a variable, e.g.:

var e = function f(p) { // (named) function expression, 
                        // storing the new function in e, 
                        // naming the function f
  // in the function body f refers to the function itself, 
  // enabling e.g. recursion.
  return p;
}; // note: expression are terminated by a semicolon in JavaScript
 
e("Hello, World!");
// note: f is not defined in this context!

Distinguishing between function statements and function expressions may be hard sometimes, since their syntax is at least similar, if not nearly identical in some cases. If the position of the function definition is a valid position for a statement, the function keyword will always introduce a function statement. If not, it will always introduce a function expression. Or more precise: if there is nothing but whitespaces between the last semicolon or curly brace (or the beginning of the file) and the function keyword then it is a function statement. Note that “nothing” really is nothing – especially no parentheses:

function s(p) { // function statement
  return p;
} // note: function statements are not terminated by a semicolon
var e = function (p) { // function expression
  return p; 
};
function s2(p) { // another function statement
  return p;
}
(function n(p) {  // named function expression
  return p;
});

Knowing the difference between a function statement and a function expression is important, especially when handling named function expressions. In contrast to function statement identifiers those names are not available outside of the function context. Also, while function expressions are terminated by a semicolon, function statements aren’t. Since JavaScript has semicolon insertion and allows empty statements (extra semicolons) your code will most likely run fine if you skip a semicolon after a function expression or add an extra one after a function statement, but if you are strict about placing those semicolons you can show off you knowledge about JavaScript functions ;)

Remember, remember, the fifth of November

One of the most powerful consequences of being able to write functions as expressions, is that you can define functions completely anonymously, without giving them a name at all. This concept is also known as lambda functions in functional languages such as Scheme. But why would you want to define a function that has no identifier attached to it? Well, since function expressions return a first-class function value, you can use that returned value just in place, like you could use any other value. One common concept is to pass that value as a parameter to another function or even call it just there:

function callFunc(f) { // function statement
  return f(); // f is considered a function and called
};
var result = callFunc(function () { // anonymous function passed 
                                    // as a parameter to callFunc
                                    // f will call the anonymous function
  return "Hello, World!";
});
// result === "Hello, World!"
 
var result2 = (function () { // anonymous function invoked in place
  return "Hello, World!";
})(); // result2 === "Hello, World!", note the invocation parenthesis: ()

While the use for the first concept is rather trivial, just think of callback-functions, the use for the second scheme might not be apparent immediately. Why would you want to define a function and call it in place? Why not simply skip the function definition? There are several use-cases.

One such use-case is to reduce scope. Although JavaScript has curly-brace blocks, such blocks do not define scope. Let me give you an example:

function f() {
  var v = 1;
  if (v) {
    var u = 1; // variable definition inside a block
  }
  if (u) {
    return true;
  } else {
    return false;
  }
}
f(); // returns true

What this means is, that unlike in C or Java in JavaScript blocks do not define scope. Instead scope if defined merely by functions. So if you want to create a new scope, e.g. to prevent leaking of identifiers into the global scope, you will have to do this with a function. Since such a functions only purpose is to reduce scope, you may want to define it anonymously and invoke it in place:

function f() {
  var v = 1;
  if (v) {
    (function () {
      var u = 1; // variable definition inside a function
    })();
  }
  if (u) {
    return true;
  } else {
    return false;
  }
}
f(); // returns false

You can use this technique to effectively reduce the scope of identifiers. The module pattern uses this approach for example to prevent identifiers leaking into global scope.

There are several other use-cases for this, e.g. if you have a recursive solution to a one-time problem, you wrap the solution in a function expression, which is invoked immediately given the start parameters. Or if you would like to have an identifier resolve to one of two different functions depending on a condition, then you could have a immediate invoking function that returns one or the other function depending on the condition.

this is ridiculous

In most modern object-oriented programming languages you distinguish between functions and methods, where functions live alone for themselves, while methods inside a class. In those languages methods are special because they receive a hidden parameter, which most languages expose as this to the method body. This special parameter this refers to the object the method was called on. But as you may learned from my other primer JavaScript is very different than most languages regarding object-orientation. This is also true for methods. Methods in JavaScript are just regular functions assigned to a member of an object. You have seen it before in one of the examples, but let me show you again:

function f() {
  return 1;
}
var o = {
  m: f
};
o.m() === 1;

As you can see o.m refers to the same function as f. In fact is is the same function as f. If you would change something on f, like adding a member, you would see this change also through o.m.
JavaScript also provides a special parameter this. However, since methods in JavaScript are nothing but functions attached to objects, it works a bit different. this is not only available in “methods” but in all JavaScript functions. It’s value is either the object on which a function was called, or if not called on any object, but as a regular function, it points to the global object in traditional JavaScript and is undefined in strict mode. What does that mean you ask? Well, have a look:

function f() {
  return this;
}
var o = {
  m: f
};
 
f() === window; // true
o.m() === o; // true
 
function s() {
  "use strict";
  return this;
}
o.m = s;
 
s() === undefined; // true
o.m() === o; // true

But that’s not all. JavaScript functions, as good first-class objects, have a couple of interesting methods themselves. Two of the most powerful are Function.prototype.call and Function.prototype.apply. call and apply allow you to call a function while explicitly specifying the value of this for that call. They are pretty much the same, except that call expects additional parameters that shall be passed to the function to be passed as regular parameters, while apply expects an array as it’s second parameter that will be passed to the invoked function as arguments.

function f (a, b, c) {
  return this + a + b + c;
}
f.call(1, 2, 3, 4) === 10; // 1 will be this, additional values as params
f.apply(4, [3, 2, 1]) === 10; // 4 will be this, additional params as array

You can do neat stuff with that. E.g. ever wondered how jQuery manages to get this to point to the current element in it’s each array iterator? Now you know.

Keepin’ it fun to the ending

That’s it. Now you know everything about JavaScript functions you absolutely must know. There’s still more to know, but I’ll let that to yourself to explore. If you know how to use it, JavaScript is very powerful and enormously fun to program. I hope I was able to share some of those fun aspects with you.