
In JavaScript functions are a type of object known as function object. You can work with function objects as though they were objects. Functions may be assigned to objects, passed in as arguments to other functions, returned from other functions. Additionally a function can be passed into an array. And this gets me to earlier in my articles when I’ve stated “almost everything in JavaScript is an object”. Let’s explore this in further detail.
Take as an example the preceding function:
function simple(){
return true;
}
Let’s query the type of simple() using the typeof operator:
console.log(typeof(simple)); //"function"
The typeof() operator returns function, as functions are a special type of object called function object. The function object inherits from the Function.prototype.object which in turn inherits from the Object.prototype object. The built in function object has pre-defined properties such as name, length and methods such as call() and bind(). Let’s have a look at a few in the upcoming paragraphs.
We can query the value of the name property of a function using the dot notation. For example, using the simple() function:
function simple(){
return true;
}
console.log(simple.name); // "simple"
This lets us know that the function’s name property has a value of “simple”. This correlates to the name of the function. We can also query the number of arguments passed into a function with the length property like so:
console.log(simple.length); // 0
The function simple() has no arguments therefore, the length property returns 0. User –
created properties may also be defined on a function however, that is not recommended. Let’s add a property to the simple() function for fun:
simple.category = 'basic';
Just as we can add properties to an object, we can do the same to functions. We have added a category property to the simple() function whose value is the string basic. Accessing the category property on the function will display its value:
console.log(simple.category); // "basic"
Existing methods on the function object are call(), bind() and apply(). The discussion of these is out of the scope of this chapter, but it is worthwhile to keep in mind that the function object has these pre-defined methods. We can also add user-created methods on the function object. For example, let’s add a rather simple method on the simple() function which will return to us a random number when called:
simple.numGen = function(){
let randomNum = Math.random();
return randomNum;
}
The numGen method of the simple() function returns a random number generated using
Math.random() . Calling it will return a random number:
simple.numGen(); //0.8845385071782436