42

1.

function abc(){
    alert("named function");
}

v/s

2.

function(){
    alert("Un-Named function");
}

Kindly explain from beginners point.

Ian
  • 50,146
  • 13
  • 101
  • 111
Maxx
  • 709
  • 5
  • 11
  • 22

2 Answers2

32

They work exactly the same. It's only in how you are able to run them that they are different.

So example #1 you could call again at any point with abc();. For example 2, you would either have to pass it as a parameter to another function, or set a variable to store it, like this:

var someFunction = function() {
    alert("Un-Named function");
}

Here's how to pass it into another function and run it.

// define it
function iRunOtherFunctions(otherFunction) {
    otherFunction.call(this);
}

// run it
iRunOtherFunctions(function() {
    alert("I'm inside another function");
});

As David mentions below, you can instantly call it too:

(function() {
    alert("Called immediately");
})(); // note the () after the function.
Jordan
  • 31,971
  • 6
  • 56
  • 67
  • 9
    For completeness, another option for the anonymous function is to immediately call (or self-call) it: `(function() { alert('something'); })();` – David Sep 16 '13 at 13:13
  • 1
    Added more examples. Thanks David. – Jordan Sep 16 '13 at 13:15
  • @Jordan, your last example needs to wrap the function like `(function(){})();` or `(function(){}());`. – canon Sep 16 '13 at 13:18
  • @user2736012 not sure what you're talking about. The 2nd example works fine. I've already fixed the missing wrapped parens on the last example. – Jordan Sep 16 '13 at 13:21
  • @Jordan: I was talking about the second example in the question. It's not valid syntax as shown. And then I was talking about your last example. You fixed it after my and cannon's comment. – user2736012 Sep 16 '13 at 13:37
  • Ah, sorry. I misunderstood what you meant. Thanks for the clarification. My answer is fully correct now. – Jordan Sep 16 '13 at 15:14
  • just wondering what is the point of such a function. it's not the same as just writing - alert("called immediately"); as long as the function gets called immediately – ruben Aug 22 '16 at 21:59
  • Named functions and functions as variables are both used in procedural and object-oriented work. Anonymous functions like the final example are normally used in events, callbacks, and promises. – Jordan Aug 23 '16 at 06:43
  • Would like to know about this kind of anonymous function (() =>{});, lets see if I fill this function ((response)=>{alert(response.data);}); – Java_Fire_Within Nov 01 '16 at 15:37
2

Both can be used to achieve the same but the main difference is the anonymous functions don't need a name. Anonymous functions are functions that are dynamically declared at runtime. They’re called anonymous functions because they aren’t given a name in the same way as normal functions.

Please refer this link

Amit
  • 2,495
  • 14
  • 22