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