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

matori82 picture matori82 · Oct 3, 2013 · Viewed 46.3k times · Source

The title sums up my question. An example that demonstrates the point would be nice.

Answer

Daniel Gimenez picture Daniel Gimenez · Oct 3, 2013

First off, there doesn't seem to be a consensus definition for inline functions in JavaScript. I consider an inline function to be a special case of a JavaScript function. An inline function is a function assigned to a variable that is created at runtime instead of at parsetime.

Anonymous functions and inline functions are practically the same, in that they are created at runtime. The difference is that an inline function is assigned to a variable and so it can be reused. In that way, inline functions work the same as a regular function.

Pre es6, anonymous and inline functions were declared similarly to regular functions using the function keyword. With the advent of es6, anonymous and inline functions could also be declared with the more compact, arrow function syntax.

Function

function func() {
    alert ('function');
} 
$('a').click(func);

Inline Function

var func = function() { 
    alert ('inline') 
};
$('a').click(func);

// Alternative es6+ inline arrow function.
let func2 = () => alert('inline');
$('a').click(func2);

Anonymous Function

$('a').click(function() {
    alert('anonymous');
});
// Alternative es6+ anonymous arrow function.
$('a').click(() => alert('anonymous'));