4

For my example code below, the use of traditional named functions and anonymous functions perform the same task.

I've read var functionName = function() {} vs function functionName() {}, and understand how the first named function is defined at run-time, whereas the second anonymous function is defined at parse-time for a script block.

My question is specifically what conditions would make one approach more suitable than the other?

function get1() {
    return 'Hello';
};

function alert1(data) {
    alert(data);
};

var get2 = function() {
    return 'Goodby';
};

var alert2 = function(data) {
    alert(data);
};


alert1(get1());

alert2(get2());
Community
  • 1
  • 1
user1032531
  • 24,028
  • 57
  • 174
  • 325

2 Answers2

0

Not having to set a name for an anonymous function is just a convenience thing since in most cases the name of the function doesn’t really matter. Most of the time anonymous functions and named functions will both do any job perfectly well.

Check this good article : HERE

Clément Andraud
  • 8,321
  • 22
  • 69
  • 140
0

Inside of a module I find it more readable to put any inner, utility functions defined such as function logfoo and function logbar below the return statement, and then rely on them being hoisted so that I can use them above/within the return statement.

var myModule = (function() {
    return {
        foo:  function() {
            logfoo();
        },

        bar: function() {
            logbar();
        }
    }

    function logfoo() {
        console.log('foo');
    }

    function logbar() {
        console.log('bar');
    }
})();
Dexygen
  • 11,681
  • 11
  • 73
  • 144