Coding Concepts - Anonymous Functions

chris_bertrand

Chris Bertrand

Posted on June 25, 2018

Coding Concepts - Anonymous Functions

What is an Anonymous Method, and when should we use them?

Definition

Anonymous Functions - In computer programming, an anonymous function (function literal, lambda abstraction, or lambda expression) is a function definition that is not bound to an identifier. Anonymous functions are often[1] arguments being passed to higher-order functions, or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfill the same role for the function type as literals do for other data types.

As with all the topics covered in the Coding Concepts series these programming ideas have been around for some time now.  Anonymous functions have been present in programming languages since Lisp debuted in 1958! My examples will once again be demonstrated in JavaScript.  The rise of JavaScript, and relatively simple nature of the language makes it easy to code against when giving examples. Having used C# for a number of years, lambda functions (the arrow function notation =>) was my first interaction with delegates and anonymous methods, and it's where my knowledge of them started.

An anonymous function is a function that is not stored, but is associated with a variable. Anonymous functions can accept inputs and return outputs, just as standard functions do.

Normal Function Definition

// run the function 
sayHello(); // See that this can be before the function declaration

function sayHello() (
  alert("Hello");
}
Enter fullscreen mode Exit fullscreen mode

Anonymous emblem.svg

Anonymous Function Definition


var sayHello = function {
alert('Hello');
}
sayHello(); // This needs to be after declaring the anon func

Enter fullscreen mode Exit fullscreen mode

So how do these 2 differ? Well the first thing to understand is that normal functions are run before any other code, meaning they do not have to be declared before the usage of them. Anonymous functions are created at run time.

If you look back at the first example, sayHello() is written before the declaration, but in the second after it! The second example would not work if it was written before, and looking at the code it makes sense, but why is that allowed? Function declaration use the function name to create a variable in the current scope. These functions can’t be used to create anonymous functions because they require the function to have a name.

Anonymous functions are declared using the function operator instead of the function declaration.

So in essence Anonymous functions don't have names!

It seems weird but it works because the declaration creates the variable for you. Not having to set a name for an anonymous function is convenient as sometimes the name of a function doesn't really matter.

You have probably used this line many times, did you ever realise it's an anonymous method?

$(document).ready(function () {
alert("Hello");
});
Enter fullscreen mode Exit fullscreen mode

When do I use them?

Single use methods are a perfect example of when to use this principle! It's also very useful when you are planning to use the method straight away, or inside an if statement or a for loop.

for(var x=0; x<=3; x++) {
var helloFunction= function() {
alert("Hello Mr " + x + ");
}
helloFunction();
}
Enter fullscreen mode Exit fullscreen mode

The function operator (Anonymous) syntax is more concise then the function declaration (Standard). It's ideal for for single line event handlers and dealing with styling DOM elements quickly. If you bind the method directly to a variable it will be easier to find the implementation and will stop issues with global scope where function names could conflict. Let's not talk about conflicts with JQuery and all the commotion that can cause. jQuery.noConflict() is used far too much in most organisations!

var wordHouse = {
 hello: function() { alert("Hello"); }
}
wordHouse.hello();
Enter fullscreen mode Exit fullscreen mode

The function operator is also an expression, so you can do cool things as above! You could expand the wordHouse to say other words. You can even create functions as items in an array and then iterate through them!

// create an array on anonymous methods
var helloToday = [
 function() { alert("Hello Monday")},
 function() { alert("Hello Tuesday")},
];

// loop over the array
for(var x=0; x< helloToday.length; x++) {
 helloToday[x]();
}
Enter fullscreen mode Exit fullscreen mode

There's load more to anonymous methods/functions and they do behave slightly differently depending on your language of choice. So have a look at the additional reading if you want to read more on the topic.


Have I missed something useful? Do you have anything extra to add? Do you use Anonymous methods in an interesting way? If so share below!

Thanks for reading.

Chris

Additional Reading

WikiBooks - JavaScript Anonymous Functions

Stack Overflow - Anonymous Functions vs Clousures

Function Declarations vs Function Operators

Self Executing Anonymous Functions

💖 💪 🙅 🚩
chris_bertrand
Chris Bertrand

Posted on June 25, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

! and ? in Typescript.
webdev ! and ? in Typescript.

October 17, 2024

Apa itu TypeScript?
webdev Apa itu TypeScript?

November 21, 2023

Coding Concepts - Generics
webdev Coding Concepts - Generics

June 21, 2018