Functions. Which way is the best?


I've noticed when Im writing functions that there are two ways(and maybe more but I don't know). If I write this:

var myFunction = function();

gives the same result as when a write this:

function myFunction();

I don't know which one is the best way or if they have different purposes. I hope someone of the most advanced students can enlight me.

thanks in advance, and sorry for my english.


It depends on whether we want immutable functions, which are hoisted to the top of the scope when the program loads and makes the first of two passes over the code. The first past hoists all declared variables (but not their assigned values or expression) and declared functions.

var myFunction        >> hoisted in the first pass
    = function () {}; >> not read until second pass
function myFunc() {}  >> hoisted in the first pass

In the above, myFunction and myFunc are both immutable identifiers with one difference, myFunction points to something which may change from time to time, whereas myFunc declares something to which it is a fixed reference.

The code block (function body) for both are the same, expressions. The declared function is locked in place, whereas the referred function expression can be swapped out, which is handy when our logic needs to point to different functions dynamically.

Consider a three-way dynamic...

function f(){ return -1; }
function g(){ return 0; }
function h(){ return 1; }
var c, k, y;
c = 0;
do {
    k = ['-',' '][Math.floor(Math.random()*2)] + Math.floor(Math.random()*100);
    y = k < 0 ? f : k > 0 ? h : g;
    console.log(k, y());
} while (++c < 20);

Output may look like this...

 77 1
 59 1
-44 -1
-9 -1
-45 -1
 33 1
 14 1
 65 1
-5 -1
 72 1
 93 1
-0 0
-99 -1
-61 -1
-61 -1
 0 0
-2 -1
-52 -1
 39 1
-4 -1

Notice that y is always a function reference that we can invoke which is dynamically switched between three different functions.

The point is that we can re-use y but we cannot re-use f, g, or h. Functions assigned to y are said to be anonymous.