-2

What do you think, which one is the better, faster, nicer solution to declare a function?

First:

(var) myFunction = function(){
//Stuff to do
};

or Second:

function myFunction() {
//Stuff to do
};

Both will work in JavaScript and JQuery. But what do you think is better?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Raphael
  • 673
  • 1
  • 9
  • 27
  • everyone loves some or the other coding style. I think the second one is still a better option, as its more readable and efficient – Rohan Nov 14 '11 at 09:24
  • possible duplicate of [Javascript: var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname) – duri Nov 14 '11 at 09:39

1 Answers1

7

Note that both behave differently - functions defined by function statement are defined before the code executes.

typeof f; //returns 'undefined'
var f = function() {};

but

typeof f; //returns 'function'
function f() {} 

(Have you also noted where I did and where I didn't use semicolon?)

Also, function statements (the second option) are forbidden in blocks. It is not defined how the following should work:

if (false) {
    function f(){}
}

thus it's possible that function f will be, although illogically, declared in some browsers. However, it's permitted to do the following:

var f;
if (some expr) {
    f = function() {};
}

Next time better search before asking a question, var functionName = function() {} vs function functionName() {}

Community
  • 1
  • 1
duri
  • 14,991
  • 3
  • 44
  • 49