Home javascript Self-Calling JavaScript Functions

Self-Calling JavaScript Functions

Author

Date

Category

What is the difference between these functions?

Or here’s from Stefanov’s example:

var result = (function () {
 return 2 + 2;
} ());
(function () {
 alert (‘watch out!’);
}) ();

Answer 1, authority 100%

There is, in general, no difference.
Douglas Crockford found the entry:

(function () {
  // body
} ());

Is correct, and the notation:

(function () {
  // body
}) ();

Wrong and dismissively calling her “dog balls”.


Therefore, use whichever you like best (I, for example, agree with Douglas, although the second option is not annoying at all).
For example, in Perl , the slogan generally states that everything must have several notation paths.
Why is JS worse? 🙂


Answer 2

Corrected code

for (var i = 0; i & lt; 4; i ++) {
(function (i) {setTimeout (() = & gt; console.log (i), 100)} (i))
}

Doesn’t work

((i) = & gt; setTimeout (() = & gt; console.log (i), 100) ( i))

Works

((i) = & gt; setTimeout (() = & gt; console.log (i), 100)) (i)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions