3

I was told that you can declare functions in JavaScript more than 1 way. ex.

// One way
function sqrt(x){
   return x * x;
}

// Second way
var sqrtAlt = function (x){
   return x * x;
}
  • What is the difference between these two function declarations?
  • The output is same but must have a reason to have two ways?
  • I am also curious about how you would use them.
  • Lastly, are there any other ways?

Thanks.

chatu
  • 305
  • 3
  • 13

2 Answers2

0

When you are defining

function sqrt(x){
   return x * x;
}

is that the function name appears in Firebug debugger.

Functions that are declared as

var sqrtAlt = function (x){
 return x * x;
 }

come up as anonymous.

Also check out this Thread

Community
  • 1
  • 1
Rahul Tripathi
  • 152,732
  • 28
  • 233
  • 299
0

They are basically the same thing, but in the second example you additionally assign the function to a variable. This way of creating a function is very useful when overriding an existing function of some object, let's say:

window.alert = function(text)
{
    // Do something ...
};
mirrormx
  • 3,969
  • 1
  • 16
  • 17
  • There is a very important difference: In the first example the function is available at the beginning of the execution context, in the second not until the assignment statement has been executed. – a better oliver Mar 17 '13 at 15:54