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.

nik7
  • 3,018
  • 6
  • 25
  • 36

2 Answers2

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) { ... }
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
  • 1
    Since all answers receive quick downvotes here, please explain why. – Jan Turoň May 20 '13 at 07:28
  • i am aware of other methods to make that work, just wanted to know why the method in question doesn't work – nik7 May 20 '13 at 07:28
  • 1
    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. – JJJ May 20 '13 at 07:29
  • I see. Recently I've found some article about it, please wait for edit... – Jan Turoň May 20 '13 at 07:31
-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.

  • 3
    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. – sdepold May 20 '13 at 07:32
  • 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 http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/ – Md Toufiqul Islam May 20 '13 at 10:42