Functions Are Variables

Though it may not seem obvious. foo is basically just a variable a reference. The function itself is the value.

A function () is an Expression ie. (a + 2). And should be treated the same! so it could be a number, undefined, null, whatever!

foo variable (reference)
() function is the value like 1,2, [1,2], null, undefined, true or false would be

foo = ()

function foo() {
    return 1;
}
 
// roughly means var foo = 1;
var foo = function() { //
 
}

Function Expression

The same as you can assign a string, number or boolean to a variable you can also assign a function.
This is known as a function expression.

var functionExpression = function() {
  // i am a function expression
}
 
var functionExpression = function foo() {
  // i am a function expression
}
 
functionExpression();

Function Expression (on the fly)

You can also pass the function through.

function foo(fn) {
   console.log('Foo');
   fn();
}
 
function bar() {
   console.log('Bar');
} 
 
foo(bar); // foo bar

Function Expression (on the fly)

You can also pass the function on the fly. This is when you only want to use the function passed through once

var foo = function(fn) {
   console.log('Hello');
} 
 
foo(function() {
  // i am a function expression on the fly
});

Anonymous and Named Functions

/ * Anonymous -- the function has no name */
 
var foo = function() {
   // foo = ();
}
 
/ * Named function (Preferred method) -- the function has a name. Names are useful. 
     Names can be seen in stack traces, call stacks, lists of breakpoints, etc. 
     Names are a Good Thing! */
 
var foo = function bar() {
   // foo = bar; // like a = b;
}

Evoke the named function

foo();

Immediately Evoked Function Expression

(function IIFE(firstname) {
  console.log(firstname);
})('John'); // final () executes the function

Immediately Evoked Function Expression (passing in global values)

var a = 2; // global space
 
(function IIFE( global ) {
    var a = 3;
    console.log(a); //  3
    console.log(global.a); // 2
})( window ); // pass through window object reference
 
console.log(a); // 2
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License