What is the difference between anonymous and inline functions in JavaScript?

In JavaScript, anonymous and inline functions are closely related concepts that are often confused. Let's explore their differences and uses.

Anonymous Functions

Anonymous functions are functions without a name identifier. They are created at runtime and cannot be called directly by name. Here's how they work:

// Anonymous function assigned to a variable
var myfunc = function() {
    alert('This is anonymous');
};

Anonymous functions are commonly used as arguments to other functions:

setTimeout(function() {
    alert('Demo');
}, 3000);

Inline Functions

An inline function is a JavaScript function assigned to a variable and created at runtime. The key difference is that inline functions are stored in variables, making them reusable throughout your code.

var myfunc = function() {
    alert('inline');
};

// Can be reused multiple times
document.querySelector('a').onclick = myfunc;
document.querySelector('button').onclick = myfunc;

Key Differences

Feature Anonymous Function Inline Function
Name No name identifier Assigned to variable
Reusability Used once, in place Can be reused multiple times
Storage Not stored in variable Stored in variable
Common Use Callbacks, event handlers Function expressions

Example Comparison

// Anonymous function - used once
[1, 2, 3].map(function(x) { return x * 2; });

// Inline function - can be reused
var doubler = function(x) { return x * 2; };
[1, 2, 3].map(doubler);
[4, 5, 6].map(doubler); // Reused

Conclusion

Anonymous functions have no name and are used in place, while inline functions are assigned to variables for reusability. Both are function expressions, but inline functions offer better code organization and reuse.

Updated on: 2026-03-15T21:22:09+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements