Coding Concepts - Anonymous Functions
Tags: webdev, typescript, beginners, javascript
Published: 2018-06-25 13:06:16

---
title: Coding Concepts - Anonymous Functions
published: true
description: What are Anonymous Functions, and when should we use them? 
tags: webdev, TypeScript, beginners, JavaScript
cover_image: https://thepracticaldev.s3.amazonaws.com/i/1p5pcm7uoppiidw7pn2x.png
series: Coding Concepts
---

<h1>What is an Anonymous Method, and when should we use them?</h1>
<h2>Definition</h2>
<blockquote><b>Anonymous Functions - In <a title="Computer programming" href="https://en.wikipedia.org/wiki/Computer_programming">computer programming</a>, an anonymous function (function literal, lambda abstraction, or lambda expression) is a <a class="mw-redirect" title="Function (computer science)" href="https://en.wikipedia.org/wiki/Function_(computer_science)">function</a> definition that is not <a title="Name binding" href="https://en.wikipedia.org/wiki/Name_binding">bound</a> to an <a class="mw-redirect" title="Name (computer science)" href="https://en.wikipedia.org/wiki/Name_(computer_science)">identifier</a>. Anonymous functions are often<sup id="cite_ref-1" class="reference"><a href="https://en.wikipedia.org/wiki/Anonymous_function#cite_note-1">[1]</a></sup> arguments being passed to <a title="Higher-order function" href="https://en.wikipedia.org/wiki/Higher-order_function">higher-order functions</a>, 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 <a class="mw-redirect" title="Functional programming language" href="https://en.wikipedia.org/wiki/Functional_programming_language">functional programming languages</a> and other languages with <a title="First-class function" href="https://en.wikipedia.org/wiki/First-class_function">first-class functions</a>, where they fulfill the same role for the <a title="Function type" href="https://en.wikipedia.org/wiki/Function_type">function type</a> as <a title="Literal (computer programming)" href="https://en.wikipedia.org/wiki/Literal_(computer_programming)">literals</a> do for other <a title="Data type" href="https://en.wikipedia.org/wiki/Data_type">data types</a>.</b></blockquote>
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 =&gt;) was my first interaction with delegates and anonymous methods, and it's where my knowledge of them started.
<blockquote>An <b>anonymous function</b> is a <b>function</b> that is not stored, but is associated with a variable. <b>Anonymous functions</b> can accept inputs and return outputs, just as standard <b>functions</b> do.</blockquote>
<h3>Normal Function Definition</h3>

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

function sayHello() (
  alert("Hello");
}
```

<h3><img class="aligncenter" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a6/Anonymous_emblem.svg/316px-Anonymous_emblem.svg.png" alt="Anonymous emblem.svg" width="195" height="195" /></h3>
<h3>Anonymous Function Definition</h3>

```javascript

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

```

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, <strong>sayHello()</strong> 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, <strong>but why is that allowed?</strong> 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.
<blockquote>Anonymous functions are declared using the <a href="http://helephant.com/2012/07/14/javascript-function-declaration-vs-expression/">function operator instead of the function declaration</a>.</blockquote>
<strong>So in essence Anonymous functions don't have names!</strong>

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?

```javascript
$(document).ready(function () {
alert("Hello");
});
```

<h2>When do I use them?</h2>
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 <strong>if statement </strong>or a <strong>for</strong> <strong>loop.</strong>

```javascript
for(var x=0; x<=3; x++) {
var helloFunction= function() {
alert("Hello Mr " + x + ");
}
helloFunction();
}
```

The function operator (<strong>Anonymous</strong>) syntax is more concise then the function declaration (<strong>Standard</strong>). 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. <strong>jQuery.noConflict()</strong> is used far too much in most organisations!

```javascript
var wordHouse = {
 hello: function() { alert("Hello"); }
}
wordHouse.hello();
```

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!

```javascript
// 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]();
}
```

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.

<hr />

<b>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! </b>

Thanks for reading.

Chris
<h1>Additional Reading</h1>
<a href="https://en.wikibooks.org/wiki/JavaScript/Anonymous_functions" target="_blank" rel="noopener">WikiBooks - JavaScript Anonymous Functions</a>

<a href="https://stackoverflow.com/questions/12930272/javascript-closures-vs-anonymous-functions" target="_blank" rel="noopener">Stack Overflow - Anonymous Functions vs Clousures</a>

<a href="http://helephant.com/2012/07/14/javascript-function-declaration-vs-expression/" target="_blank" rel="noopener">Function Declarations vs Function Operators</a>

<a href="http://esbueno.noahstokes.com/post/77292606977/self-executing-anonymous-functions-or-how-to-write" target="_blank" rel="noopener">Self Executing Anonymous Functions</a>