43

1.

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

v/s

2.

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

Kindly explain from beginners point.

6
  • 2
    The one with a name can be referenced by that name. The one without a name can't, it's "anonymous." Functionally they're identical. Commented Sep 16, 2013 at 13:10
  • Just try to call the function in your second example. Commented Sep 16, 2013 at 13:12
  • 1
    The second one is invalid syntax, and the code will throw a SyntaxError. To be used without a name, it will require evaluation within some expression. Commented Sep 16, 2013 at 13:18
  • 1
    Up-vote + Thank you for asking Commented Dec 2, 2016 at 14:33
  • what about this one: setTimeout (() => {}, time) ???? Commented Nov 27, 2017 at 21:11

2 Answers 2

33

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.
Sign up to request clarification or add additional context in comments.

9 Comments

For completeness, another option for the anonymous function is to immediately call (or self-call) it: (function() { alert('something'); })();
Added more examples. Thanks David.
@Jordan, your last example needs to wrap the function like (function(){})(); or (function(){}());.
@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: 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.
|
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.