Alessandro Lacava

on Designing and Developing Software. In love with Functional Programming.

The Function Class In JavaScript

Most programmers know how to define and use a function in JavaScript. For example the following function displays an alert containing the string passed in as a parameter:

1
2
3
4
5
function displayAlert(sText) {
  alert(sText);
}
// Then you call it this way
displayAlert("Hello World!");

How many developers, however, know that JavaScript functions are actually objects? Indeed, you can define the previous function using the Function class:

1
2
3
var displayAlert = new Function("sText", "alert(sText);");
//...and you call it the same way
displayAlert("Hello World!");

For those who didn’t figure it out, the syntax of the Function class is the following:

1
var functionName = new Function(arg_1, arg_2, ..., arg_n, functionBody);

where arg_i (i = 1,…,n) is the i-th argument and functionBody is (you guessed it) the body of the function. Although you can define functions using the Function class it’s best to avoid it because it’s less performant than the traditional way. Anyway, knowing that even a function is an object is useful because you know you can call on it the valueOf() and toString() methods shared by all objects. However, when called on a function, these two methods return the source code for the function as a string. You can also call the one property defined in ECMAScript which is length. This property returns the number of arguments as defined in the function. For example:

1
2
3
4
5
function displayAlert(sText) {
  alert(sText);
}
//display an alert containing the number of arguments (in this case 1)
alert(displayAlert.length);

Comments