Functions are first class objects in javascript

Functions in javascript are first class objects. This means that javascript functions are just a special type of object that can do all the things that regular objects can do.

Really, just like any other variable

Here are a few of the important objects things that you can do with a function in javascript.

A function is an instance of the Object type:

  1. function feedCat(){
  2.     alert("Kibble, tinned food and water");
  3. }
  4. alert(feedCat instanceof Object);

A function can have properties and has a link back to its constructor method:

  1. feedCat.food = "kibble";
  2. alert(feedCat.food);
  3. alert(feedCat.constructor);

You can store the function in a variable:

  1. function feedCat(){
  2.     alert("Kibble, tinned food and water");
  3. }
  4. var eveningChore = feedCat;eveningChore();

You can pass the function as a parameter to another function:

  1. function doEveningChores(chores){
  2.     for(var x=0; x<chores .length; x++)
  3.         chores[x]();
  4. }
  5. doEveningChores([feedCat]);

You can return the function from a function:

  1. function tonightChores(){
  2.     return feedCat;
  3. }
  4. var tonight = tonightChores();
  5. tonight();

Complete example.

Can reduce repetitive code

Being able to pass logic around an application in the form of a function means it’s possible to move a lot of repetitive code into a library function. It makes it easier to separate the unique pieces of logic from the generally useful logic.

For example, imagine you have a list of chocolate bars and you want to find all the ones that are made by Mars because you love M&Ms and you want to find out what other chocolatey goodness you could be enjoying (I have been on a diet for seven months.. I content myself with imagining chocolate..).

You could write a loop to iterate through the complete list and apply your item selection logic like this:

  1. var chocolateBars = [
  2.     {name: "Galaxy", manufacturer: "Mars"},
  3.     …];
  4. var marsChocolate = [];
  5. for(var x=0; x<chocolatebars .length; x++){
  6.     if(chocolateBars[x].manufacturer == "Mars")
  7.         marsChocolate.push(chocolateBars[x]);
  8. }

That’s great! Problem solved. Only now it’s Christmas time in your application and you have to sort the naughty list from the nice list. You’re always so busy at this time of year! Plus you learnt in programmer school that you shouldn’t have to write the same thing twice.

This sounds like the job for a library function! Let’s split the thing that will be the same each time (walking the existing list, building the new list) from the thing that will be different each time (applying the filter). The walking the list and building the new list logic can go into a library function. The filtering logic can be passed in as a parameter:

  1. var array_helper = {
  2.     filter: function(list, filter)
  3.     {
  4.         var matches = [];
  5.         for(var x=0; x<list .length; x++)
  6.         {
  7.             if(filter(list[x]))
  8.                 matches.push(list[x]);
  9.         }
  10.         return matches;
  11.     }
  12. };
  13. var marsChocolate = array_helper.filter(chocolateBars,
  14.      function(item) { return item.manufacturer == "Mars"
  15. });
  16.  
  17. var naughtyList = array_helper.filter(childrenOfTheWorld,
  18.     function(item) { return item.naughtiness &gt; 50;
  19. });
  20.  
  21. var niceList = array_helper.filter(childrenOfTheWorld,
  22.     function(item) { return item.naughtiness &lt;= 50;
  23. });

Complete example (except for the naughty list – I wouldn’t presume to take Santa’s job).

Now the code that actually needs to be written for each list that needs filtering is really simple. If there’s a problem in this logic it will be dead easy to spot. Any problems with the logic in the library function can be fixed in one place in the code. Plus you can get a list of delicious confectionery any time you want and the good children of the world will all get their presents at Christmas time.

The filter function is such a useful idea that it’s a part of popular javascript libraries like JQuery and Dojo. It will also be included in the browser as a standard part of Javascript 1.6. However the same idea can be applied in a lot of different places to reduce the amount of repeated code that’s not really pulling its weight.

Methods are properties that contain functions

Object methods are nothing special in javascript. They just are properties that happen to contain a function rather than something like a string or number value:

  1. var sabby = {
  2.      name : "Sabby",
  3.      species: "cat",
  4.      hello : function() { alert("hissss"); }
  5. };

This was pretty clever of the javascript language designers because it meant that they didn’t need to do anything special to support object methods. This is part of the reason why javascript can have objects without having classes.

Makes javascript flexible and dynamic

A lot of javascript’s flexibility comes from being able to treat functions as first class objects. Pretty much every example in the javascript objects articles takes advantage of being able to treat a function just like a regular object.

All of the basic techniques for using objects in javascript rely on this one thing. Simple objects, constructor functions and prototypes all involve assigning methods to the properties of an object.

It also helps javascript to be flexible and lightweight. Useful ideas from other languages like namespacing, custom events, static methods and extension methods can all be simulated because it’s possible to create a function and put it wherever you need.

Further reading

The best reference I could find about this was an article about functional javascript. It explains a heap of the functional language features that javascript has.

Raganwald has an interesting article with some more general information about why techniques like this are so useful. It compares ruby and java but the logic still applies to javascript.

What’s next?

Anonymous functions are functions that are dynamically created at runtime using the function operator. Anonymous functions go hand in hand with functions being first class objects because these are two of the big things that javascript such a flexible and dynamic language.

This article is part of a set of related posts about How javascript objects work.

Posted on 19 Aug 08 by Helen Emerson (last updated on 01 Oct 11).
Filed under Javascript

Comments

Fatima 08 Jun 2010

i like your explanation so much, i didn’t know where to report you with a broken link line(258) http://helephant.com/article.aspx?ID=1194

helen 12 Jun 2010

Thanks for the kind words. I’ve fixed up the broken link now.

Jamie 30 Sep 2011

Great articles, Helen. I’d like to point out on this article that, in the first example, instanceOf contains a capital “O”. I’m only mentioning because, as a newbie to instanceof, I spent half an hour wondering why that code didn’t work when I copied it to FF console. :P

Again, thanks for the articles. They’re really well put together.

john 17 Oct 2011

These are two parts of your blog that I find confusing/contradicting, and if you could explain to me how it is possible that the first example assigns the eveningChore variable to a function feedcat without putting the () after. var eveningChoire=feedCat and not eveningChore=feedcat(), yet for example 2, var tonight= tonightChores() with the (). When assigning a function to a variable, should I be adding the () or not?
1)

function feedCat(){
alert(“Kibble, tinned food and water”);
}
var eveningChore = feedCat;eveningChore();

2)

function tonightChores(){
return feedCat;
}
var tonight = tonightChores();
tonight();

helen 22 Oct 2011

First example assigns a function to a variable and then runs the function.

Second example executes another function called tonightChores which returns a different function called feedCat and then executes feedCat.

Parentheses after the function name means you want to execute the function. No parentheses means you want to assign the function object itself to a variable.

Mickey 27 Dec 2011

Thanks so much! I am so afraid of Javascript…seem like you have tamed it for a bit here :)

Decki 10 Jun 2012

You can pass the function as a parameter to another function:

function doEveningChores(chores){
for(var x=0; x<chores .length; x++)
chores[x]();
}
doEveningChores([feedCat]);

can you explain this a bit more? are you passing an array [feedCat}? the intention is to pass a function? thanks a lot

Jon 08 Jul 2012

I have the same question as Decki. Can you explain Example 4 a bit more? Tell me if i am wrong:

Line 1: I see that the chores parameter is just a placeholder name (and could be renamed anything. feedCat is a chore : )
Line 2: Next I see that the for loop is looping through chores.length, or each parameter held in feedCat.
Line 3: For each parameter we have, execute it.

What I do not get is, why put square brackets around feedCat in Line 5?

Thanks

Helen Emerson 08 Jul 2012

@Decki: Yes, my intention is to pass an array of functions.

@Jon: Chores is a list of chore functions. It’s possible to add multiple chore functions and have them all executed. The feedCat variable contains just a single function. Putting the square brackets around the feedCat function creates a list with one item. If I passed in feedCat without the square brackets, as soon as doEveningChores started trying to go through the list, it would have problems because feedCat doesn’t have a length or any items in it.

To be honest, the example isn’t very good. It would be better if it passed in multiple chores (so you can see that it is a list) or if it was just a simpler example of passing a function to a function.

I was trying to illustrate why you might want to pass a function into a function as a parameter. In this case, the reason is to separate a common part of your algorithm (for example, looping through a list and applying a function to every item) from the part that changes every time (which might be performing some action on every item in the list).

A more common reason of why you’d want to pass a function as a parameter to another function is because you wouldn’t want to use the function straight away. For example it might be to set up some timer logic or to handle an event. JQuery does this all the time. The other reason is to separate a common part of your algorithm (for example, looping through a list and applying a function to every item) from the part that changes every time (which might be performing some action on every item in the list).

My example doesn’t really explain either of this things very well! I’ll make myself a note to update it. Thanks for the questions.

Murugaprabu 10 Sep 2012

Awesome post. I have started to really think functions as an object only after reading this tutorial. Thanks a lot. Your explanations are very simple and to the point. Luv it a loooottt…. :-)

Trackbacks