Understanding Function Objects in JavaScript

Charles Hughes
2 min readMar 17, 2014

--

One of the essential concepts in JavaScript programming is the function object. Function objects are pretty complicated, multi-facetted beasts. To fully grasp function objects in JavaScript, we need to have a solid grasp of a couple different things: the keyword “this”, scopes or environment variables, and closures. All three of these things are concepts that are fairly abstract without many analogous things in our daily lives to compare them to. I feel it is for this reason that they are often misunderstood. I hope to help clear these concepts up for some people with a few blog posts.

So first of all, in its most basic form, what is a function object? Without any of the fancy whistles and bells that I’ll be talking about later, a function object is simply an object in memory that represents a function. This function can be executed at will by putting some parentheses after its variable name.

var function_object = function(){
alert(“I’m a function object! Look at me!”);
};
function_object();

You might be thinking “Well, that looks just like a function to me. What makes it a function object?” The bare bones example above only illustrates the function part of function objects in Javascript and not the object part. So what makes a function object a function object? One example of the object property of Javascript functions is that you can pass a function as a parameter to other functions:

var another_function_object = function(callback){
callback.call();
};
another_function_object(function_object);

It might not seem like much right now, but this ability is very powerful and has deep implications for the power you can wield when writing Javascript code.

So not only can you pass a function as a parameter to another function, but you can return a function from within another function, set a function as a property of an object, store a function in an array… You can basically do anything with a function that you can do with any other object in Javascript. You can even assign additional properties to a function:

var fun = function(){
return 1;
};
fun.newProp = “I’m a property!”;
fun.newProp; // returns "I'm a property!"

I’m not sure why you would be tempted to do that, but you can!

So now that we have the basics down, lets explore the other facets of function objects in Javascript that make them so fun and interesting. First, we will start off with an introduction to the keyword “this”.

This is part one of a five part series (1, 2, 3, 4, 5). The next post is What is “this”.

--

--