1// There are several definitions
2
3// Non-anonymous, you name it
4function hello() { /* code */ }
5// Call as usual
6hello()
7
8// The myriad of anonymous functions
9
10// This is actually anonymous
11// It is simply stored in a variable
12var hello = function() { /* code */ }
13// It is called the same way
14hello()
15
16// You will usually find them as callbacks
17setTimeout(function(){ /* code */ }, 1000)
18// jQuery
19$('.some-element').each(function(index){ /* code */ })
20
21// Or a self firing-closue
22(function(){ /* code */ })()
1// (param1, param2, paramN) => expression
2
3// ES5
4var multiplyES5 = function(x, y) {
5 return x * y;
6};
7
8// ES6
9const multiplyES6 = (x, y) => { return x * y };
10
1// ES5
2var multiplyES5 = function(x, y) {
3 return x * y;
4};
5
6// ES6
7const multiplyES6 = (x, y) => { return x * y };
1//Anonymous function; It's not assigned to an indentifier
2
3Array.forEach((arguments) => {
4 //This is an anonymous function
5})
6
7function forEach(arguments) {
8 //This is NOT an anonymous function
9}
10
1// Arrow functions
2// ES6 introduced arrow function expression that provides a shorthand for declaring anonymous functions:
3
4// For example, this function:
5
6let show = function () {
7 console.log('Anonymous function');
8};
9// Code language: JavaScript (javascript)
10// … can be shortened using the following arrow function:
11
12let show = () => console.log('Anonymous function');
13let show = (variable) => { /* code */ }
14// Code language: JavaScript (javascript)
15// Similarly, the following anonymous function:
16
17let add = function (a, b) {
18 return a + b;
19};
20// Code language: JavaScript (javascript)
21// … is equivalent to the following arrow function:
22
23let add = (a, b) => a + b;
1// Regular function, called explicitly by name .aka “named function”
2function multiply(a, b){
3 var result = a * b;
4 console.log(result);
5}
6multiply(5, 3);
7
8// Anonymous function stored in variable.
9// Invoked by calling the variable as a function
10// Anonymous functions don't have a name,
11// so the parentheses appears right after “function” keyword.
12var divided = function() {
13 var result = 15 / 3;
14 console.log("15 divided by 4 is " + result);
15}
16divided();
17
18// Immediately Invoked Function Expression.
19// Immediately invoked function expressions are anonymous functions
20// with another parentheses pair at the end to trigger them,
21// all wrapped inside parentheses.
22// Runs as soon as the browser finds it:
23(function() {
24 var result = 20 / 10;
25 console.log("20 divided by 10 is " + result);
26}())
27