What is an anonymous function?

Question

What is an anonymous function?

Answer

An anonymous function is a function without a name! Anonymous functions are commonly assigned to a variable name or used as a callback function.
Syntax for anonymous function:

function (optionalParameters) {
  //do something
}

Anonymous function assigned to a variable:

const myFunction = function(){
  //do something
};

Anonymous function used as a callback function:

[1, 2, 3].map(function(element){
  //do something
});
1 Like

Austensibly an anonymous function is an expression, and not a declaration. When we add a name before the parameter in the first example above, it becomes a declaration and would be freestanding. As such it would be hoisted at load time. Expressions are never hoisted and only get picked up on the second pass through the code by the parsing engine. Unless they are callbacks in an iterator or event handler they are always assignments and get bound to a variable.

If we use const then it becomes a permanent function. If on the other hand we use var or let our expression can be replaced. That means we can assign new functions to a variable (just don’t try to use let again, and we should know by now not to redeclare variables, so var is off the table, too). A simple assignment is all that is needed to replace an expression.

Consider what might be done with this construct…

lib = [x => --x, x => x, x => ++x]

This run took 275 iterations (of which 100 were zero sum) to play out. It might never have, that’s the risk we took, but it did.

x = 9;
while (x > 0) {
  x = lib[Math.floor(Math.random() * 3)](x);    // function expression invoked
  console.log(x);
}
Trial run
	10
	9
	10
	11
2	10
	9
	10
	11
2	12
2	11
	10
	11
	10
	9
2	10
6	11
	10
	11
	12
	13
	12
	13
	14
	15
	16
4	15
	14
	15
	14
	15
	16
3	17
2	18
	19
	18
	19
2	20
	21
2	20
	19
	20
2	21
	20
3	19
	20
	21
	22
	21
	22
6	21
	22
	23
	24
2	25
2	24
4	25
4	26
	27
	26
4	25
	24
	25
3	26
	25
2	24
	25
2	24
	23
	24
3	25
	24
2	23
	24
3	23
2	22
	23
	22
3	23
	24
	25
	26
2	27
	26
4	27
6	26
2	27
	28
7	29
	30
	29
	30
	31
	30
	29
	28
	27
	26
	25
	26
	25
2	26
	25
	24
2	23
	22
	21
2	22
2	21
5	22
2	23
	22
	23
	24
	23
2	22
	21
2	22
	23
	22
2	21
	22
3	23
	22
	23
	22
2	21
3	20
	19
	18
4	19
	18
2	17
	18
	17
	16
	15
	14
	13
	12
	11
2	10
2	9
	8
2	9
	10
3	9
	8
	9
2	8
	7
	8
	7
	8
	7
	6
	5
	4
2	5
	6
	5
	4
	5
3	6
	5
	4
	3
5	4
	5
	4
	3
	2
	1
2	2
2	1
	0
undefined	275

In case you’re wondering how I got that number, the left column contains repeat counts. I dropped the tabulated data into Excel and inserted a formula in the last, rightmost cell after labeling the left column “zeros” (sans the ‘defined’)…

=ROWS(zeros) + SUM(zeros)-(ROWS(zeros) - COUNTBLANK(zeros))
4 Likes

How does this part work ? lib[???](x)
I know what Math.Random does.
I whas wondering how [] is used in this case and how this works ?

lib is an arbitrary name given to the an array of function expressions. The line above accessess a random index of the array (that’s what [] is for) and invokes the function on the parameter, x.

1 Like

Technically if you assign it to a variable it’s not really anonymous because it can be called through the variable.

Yes, but the function still does not have a name, and it is an expression, not a hoistable function. A variable is a name for a given reference, which reference may be any object, such as a function expression. Assignments are from right to left. The object on the right is an anonymous function. No further semantics involved.

Because they are expressions, we can write/insert them anywhere a value would appear.

list = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
lmap = list.map(x => 2 ** x)

The expression between the parens is an anonymous function.

// [1, 2, 2, 4, 8, 32, 256, 8192, 2097152, 17179869184, 36028797018963970]
3 Likes

Sorry for trailing off-topic in this FAQ, but why would the creators of JS allow hoisting?

You make it sound like a bad thing. It’s not. Just how JavaScript compiles declarations.

function foo() {
    console.log(a)
}
foo();    // undefined
var a;

These are hoistable declarations. Notice that no ReferenceError exception is raised?

SERP: what is hoisting?

I don’t think it’s a bad thing; it could be helpful. But why are there some unhoistable things and some hoistable things?

There is plenty of good reading in that SERP, above. Surely you can find out more about hoisting by doing a little digging on your own.

What does this imply?

Nothing is implied. Hoisting is simply assignment of scope, and declared variables go to the top of their respective scope making them accessible even if they are called before the line in which they are declared.

console.log(foo('foobar'))    // call before declaration

function foo (bar) {
    return bar.toUpperCase()
}

Console Output

FOOBAR

This only works for declared functions, not function expressions which cannot be called before they are declared.


edited by mtf 24 Nov 2021 - foobar → FOOBAR

1 Like

Hey man, really appreciate your contribution to the forum. But sometimes your explanations are quite verbose and full of technical jargon. Obviously the concepts are very technical but what I understand that folks on this platform are very noobs in programming. For the question - what is an anonymous function you went into hoisting , lib, variable declaration etc. Which I think makes the reader more confused.

3 Likes

That’s one opinion. It’s the humble opinion of this noob that we need more contributors like @mtf to keep things highly challenging and interesting. I like his ‘extra study’ posts and that he often provides supplemental information. This is an educational forum and I personally have learned more from mtf’s objective contributions than from those of any other single community member thus far. I find mtf’s style thought provoking which only serves to elevate this forum and prevents topics from getting too watered down.

2 Likes

Learn by awares, not by rote. Disregard the err and study the idea.

2 Likes