0
function (){
    alert('a function');
}

when i put it on the firebug javascript control. it shows function statement requires a name

(function (){
    alert('a function');
}())

when i put the above it shows ok.

function (){
    alert('a function');
}()

it also shows function statement requires a name and doesn't execute the function. why?

run
  • 543
  • 4
  • 8
  • 20
  • possible duplicate of [What do parentheses surrounding a JavaScript object/function/class declaration mean?](http://stackoverflow.com/questions/440739/what-do-parentheses-surrounding-a-javascript-object-function-class-declaration-m) – Quentin May 16 '12 at 10:31
  • 1
    http://stackoverflow.com/a/442408/1113426 – Engineer May 16 '12 at 10:35

1 Answers1

1
function (){
    alert('a function');
}

is a function statement, so it requires a name.

(function (){
    alert('a function');
}())

The () change the statement to an expression, so it's OK.

And you could also use the below ways.

(function (){
    alert('a function');
})();

!function (){
    alert('a function');
}();

+function (){
    alert('a function');
}();
xdazz
  • 158,678
  • 38
  • 247
  • 274