Stop writing anonymous functions

Today I want to talk to you about anonymous functions in Javascript and how we can write our code in such a way to get the most out of our development tools. But first:

p_anonymous-function

What are anonymous functions?
In javascript you can create a function in two ways, through a function declaration or through a function expression.

Using a function declaration looks like this:

function hello() {                  // <-- creates a function named 'hello'
  alert('Hello World!');
}

Using a function expression looks like this:

var hello = function() {            // <-- creates an anonymous function assigned
  alert('Hello World!');            //     to a variable named 'hello'
};

You can even combine the two approaches:

var hello = function hello() {      // <-- creates a function named 'hello'
  alert('Hello World!');            //     assigned to a variable named 'hello'
};

So there is a variety of ways to create a new function. Which is best?

Disadvantages of anonymous functions
In browsers that support the name attribute on function objects there will be no name available for the second helloWorld function. Why not? Because it might as well have been created like this:

var x = y = z = function() {...};

So in a function expression like this, which would be the one and only real name of the function? Or what to do with auto-invoking function expressions such as this:

(function() {
})();

Apart from the name variable, we also won’t get a name for these functions in stack traces or as the source of log messages. These are valuable debugging tools. We should write our code in such a way as to be able to get maximum benefit of these tools.

Changing our ways
Anonymous functions are often used as part of literal object expressions, like this:

var Speaker = {
  speak: function() {
    alert('Hello World!');
  }
};

What I am proposing is that we built in some redundancy in these types of code, to aid our development tools, and write such code like this:

var Speaker = {
  speak: function Speaker_speak() {
    alert('Hello World!');
  }
};

One day you’ll have to debug some very weird issue happening only in production of which you only have some logging and then you’ll thank yourself for putting in the extra typing to make sure your functions are not all anonymous!

What do you think?
Let me know your take on this in the comments.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s