javascript anonymous functions 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: js anonymous functions

// ES5
var multiplyES5 = function(x, y) {
  return x * y;
};

// ES6
const multiplyES6 = (x, y) => { return x * y };

Example 3: An anonymous function

(function() {
    console.log('Code runs!')
})();

// or

!function() {
  console.log('Code runs!')
}();

Example 4: anonymous functor

1 int function (int a) {
 2   return a + 3;
 3 }
 4 
 5 class Functor {
 6   public:
 7     int operator()(int a) {
 8       return a + 3;
 9     }
10 };
11 
12 int main() {
13   auto lambda = [] (int a) { return a + 3; };
14 
15   Functor functor;
16 
17   volatile int y1 = function(5);
18   volatile int y2 = functor(5);
19   volatile int y3 = lambda(5);
20 
21   return 0;
22 }