anonymouse function in javascrpt code example

Example 1: 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 2: 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;