DEV Community

Hannah Glazier
Hannah Glazier

Posted on

A Function With No Name

Anonymous functions in JavaScript, how and when to use them.

As I settle into my early developer days and adjust to this new and confusing learning path, I am noticing some common confusions and sticking points amongst me and my fellow learners. Anonymous functions, in particular, have been a big roadblock for me. You are navigating the new world of function declarations and function expressions and then, BOOM, you are hit with the doozy that is anonymous functions! Whether you are in college, self-teaching, or going the bootcamp route like me, these nameless little first-class objects are bound to cause some confusion. So, let's try and unpack the how's, whys, and when's of anonymous functions.

Let's first take a few steps back and go over JavaScript functions in general. In JavaScript, functions act as our little helper tools used to manipulate, test, and analyze our data. We can create and use functions for all manner of things. At the base level, we can call on them to simply print our data to the console and aid us in checking our work, or we can go as far as to employ them to change our data entirely.

Named Functions:

function iHaveAName (){
  console.log('I have a name!')
};

iHaveAName();

function iAlsoHaveAName(name){
  return `My name is ${name}`
};

iAlsoHaveAName('name');
Enter fullscreen mode Exit fullscreen mode

These functions both have names and, providing they are in the global scope, these names and functions can be called on at any time. *** It should be noted that functions can also have or not have parameters. Named functions are particularly useful for dynamic code in which you will be reusing and calling on the same function multiple times for a variety of uses.

So if we want to name functions for reusability, when do we want to employ anonymous functions? Let's start with the definition:

"An anonymous function is a function that is not tied to any identifier."

The most common use for anonymous functions is as a callback function. A callback function is a function nested inside (or called upon by) another function. Anonymous functions are generally saved for when we only want to use the function once(i.e. as a callback), in a very specific instance, so it doesn't need to be accessed in any outside scope.

Anonymous Function as a Callback:

btn.addEventListener('click', function() {
  btn.innerText = "I have been clicked!"
})
Enter fullscreen mode Exit fullscreen mode

This function is adding an event listener to a button so that it will respond when clicked. The anonymous function is called as the second argument and changes the button's text to "I have been clicked!" when it is clicked. Because this response is only needed for this specific button, we are able to use the anonymous function inside of the larger function. It doesn't need a name because it will not be used anywhere else. If we wanted this response for multiple buttons, we could give the function a name like, clickResponse(), and declare it in the global scope to be called upon at any point.

Another way to accomplish this is to use a different type of anonymous function, the arrow function.

"An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations."

All arrow functions are anonymous functions and they take their anonymous nature to the next level and don't even require the function keyword!

Arrow Functions:

btn.addEventListener('click', () => btn.innerText = 'I have been clicked!')
Enter fullscreen mode Exit fullscreen mode

This function performs the exact same task as the previous function, but it doesn't require the function keyword and it can be all on one line. Arrow functions are a great way to simplify and clean up your code when you only need them to accomplish a simple task.

There is one final type of anonymous function that I want to touch on (because I found it super confusing) and that is the anonymous function expression. They are written as such:

Anonymous Function Expression:

const whatsInAName = function(){
  console.log('I am anonymous!')
};
whatsInAName();
Enter fullscreen mode Exit fullscreen mode

At first glance, it looks like this function is a named function because it is set to a variable. However, the function doesn't actually begin until the right of the "=" which makes it anonymous! These types of functions require the function keyword and can be called on as callbacks or in other places in your code, as long as they are within the correct scope.

The large variety of functions can be confusing in the beginning and you will often find yourself questioning which type is appropriate for your current task. A good rule of thumb is to name your functions when you want them to be reusable and dynamic. When your functions only need a limited scope (like with a callback) or you are trying to simplify your code, you should utilize anonymous functions.

Top comments (0)