Keywords or Variables

Named and Anonymous Functions

Todd Motto by Todd Motto Google Developer Expert Icon Google Developer Expert
JavaScript Icon

Learn JavaScript the right way

Premium JavaScript courses to skyrocket your skills to the top.

5x Courses: Basics, Masterclass, HTML5 APIs, DOM, Testing with Jest.

Functions with names are known as “named functions”, and those without are “anonymous”.

A function declaration adds a name after the function keyword, therefore becomes a “named function declaration”:

// named function declaration
function drink() {}

As these functions have names, they can be “identified”. This means they can be used as many times as you’d like, making them highly reusable units.

Named functions also have a property which holds a value:

function drink() {} // 'drink'

Named functions are useful, they help with debugging through error stack traces, call stacks and even breakpoints.

Anonymous functions contain no identifier, and are usually seen in places like callbacks:

// anonymous function as callback
element.addEventListener('click', function() {});

As anonymous functions are given no name, their property contains an empty string:

(function (){}).name // ''

This design can make them harder to pinpoint when debugging, as the JavaScript compiler cannot reference them directly.

It is often beneficial to break out an anonymous function into a named function:

function handleClick() {}

// named function as callback
element.addEventListener('click', handleClick);

This also makes the function reusable and easy to test.

Anonymous functions assigned to variables now create a value, which is a common practice in modern JavaScript and functional programming.

This practice is known as an “anonymous function expression”:

// anonymous function expression
const eat = function() {}; // 'eat'

The JavaScript compiler now infers the name of the function when an anonymous function is assigned to a variable. In previous years, the anonymous function expression’s name would be empty.

Interestingly, “anonymous function expressions” can become “named function expressions” by giving them a name:

const eat = function sleep() {}; // 'sleep'

This changes the value of the name property as the assigned function name now takes priority.

What’s more, a named function expression creates a scoped identifier that can be used within itself:

const eat = function sleep() {
  console.log(sleep); // ✅ ƒ sleep() {...}

// ❌ Uncaught ReferenceError: sleep is not defined

This allows the function to reference and invoke itself, called recursion.

Creating Functions

« Function Declarations and Expressions

Parameters and Arguments

Function Parameters and Defaults »