2
var add = function addnums(a,b)
{
    return a+b;
}
alert("sum is " + addnums(10,20));

why can't i use addnums directly in the above Javascript ?

PS : I know other alternatives, the question is why the above specified method doesn't work.

3
  • Can you have two names....?? Commented May 20, 2013 at 7:25
  • Good question :) I expected that it would just work the way you did it. So that you can either call the function via addnums(1,2) and via add(1,2). Commented May 20, 2013 at 7:27
  • 2
    addnums() wont be visible in outer scope, its a Named Function Expression Commented May 20, 2013 at 7:27

2 Answers 2

0

You can.

var add = function addnums(a,b)
{
    return a+b;
}
alert("sum is " + (function(a,b) { return a+b; })(10,20) );

Plus you may shorten the syntax:

var addnums = function(a,b) { ... }

or

function addnums(a,b) { ... }
Sign up to request clarification or add additional context in comments.

4 Comments

Since all answers receive quick downvotes here, please explain why.
i am aware of other methods to make that work, just wanted to know why the method in question doesn't work
You're not answering the question. The question is about why the function can't be referred to as addnums after it's been declared.
I see. Recently I've found some article about it, please wait for edit...
-1

You have an error writing the function write like the following:

var addnums = function(a,b)
{
    return a+b;
}
alert("sum is " + addnums(10,20));

:)

var add; is a declaration. Here add is declared and assigned a function you need not name the function after keyword function, variable name will take the function name when you define a function in this way. I think you understand now.

2 Comments

Besides the fact, that the syntax of the questioners code is correct, he wants to know why the named function isn't callable via its name.
function expression does not need a name, even if you name it it will not be called by that name. This is anonymous. You can say it is a drawback but there are more advantages than disadvantages. Check out this link javascriptweblog.wordpress.com/2010/07/06/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.