4

I found a strange behaviour in Javascript:

function() {
    return 10;
}();

This construction doesn't work on all browser because it has a syntax error. But this construction works (returns ten):

+function() {
    return 10;
}();

Why?

David Robinson
  • 71,331
  • 13
  • 150
  • 174
ilfroloff
  • 41
  • 2

1 Answers1

2

The + lets the js engine make the difference between this function expression and a function definition.

For more readability, we usually use

(function() {
    return 10;
})();

See related article

Denys Séguret
  • 335,116
  • 73
  • 720
  • 697
  • I think it's better to put the execution parens inside the outer parens, `(function () { return 10; }());` – ErikE Mar 26 '13 at 20:14
  • @ErikE Why ? I think the form I gave is the most common one, and in my opinion it's easier to see that the function is called. – Denys Séguret Mar 26 '13 at 20:16
  • I think my suggestion is easier to see that the function is called. The developer reading it can't see the first end parenthesis and think it is done... the function invocation is attached to the function itself and can't get lost. What if there are spaces between, as in `(function () { return 10; }) [spaces _ _ _ ] ();`? This could be confusing, but `(function () { return 10; } [spaces _ _ _ ] ());` very clearly shows that the parentheses belong to something before it. – ErikE Mar 26 '13 at 20:27