Functions as Objects
We discussed how functions are values in JavaScript. So we should be able to use the typeof operator to check the type of a function.
function add(x, y) {
return x + y;
}
console.log(typeof add); // "function"
That seems reasonable, except that we never defined “function” as one of the data types in JavaScript. typeof returns “function”, but functions in JavaScript are objects.
Functions are a special type of object called Function objects. That is why functions can do everything other objects can do, such as being stored in variables, passed as arguments, and so on.
Creating Functions Using the Function Constructor
Just like other objects in JavaScript, functions can be created at run time using the Function constructor. The constructor takes strings as arguments: first the parameters, then the function body.
const multiply = new Function("x", "y", "return x * y;");
console.log(typeof multiply); // "function"
console.log(multiply(2, 3)); // 6
The Function constructor does define a function, and it can be useful when a program builds code at run time, but you are unlikely to write it or run into it in real JavaScript code. The common ways to define a function are function declarations and function expressions.
Properties and Methods of Function Objects
Since functions are objects, they come with built-in properties and methods. For instance:
function add(x, y) {
return x + y;
}
console.log(add.name); // "add"
console.log(add.length); // 2 (the number of parameters)
console.log(add.toString()); // "function add(x, y) { return x + y; }"
These properties are useful when you are debugging, and in programs that handle functions as first-class citizens and need to inspect them at run time.