Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The way I usually explain this to people is to show how it's similar to other JavaScript patterns.</p> <p>First, you should know that there are two ways to declare a function (actually, there's at least five, but these are the two main culprits):</p> <p><code>function foo() {/*code*/}</code></p> <p>and</p> <p><code>var foo = function() {/*code*/};</code></p> <p>Even if this construction looks strange, you probably use it all the time when attaching events:</p> <p><code>window.onload=function(){/*code*/};</code></p> <p>You should notice that the second form is not much different from a regular variable declaration:</p> <pre><code>var bar = 5; var baz = 'some string'; var foo = function() {/*code*/}; </code></pre> <p>But in JavaScript, you always have the choice between using a value directly or through a variable. If <code>bar</code> is <code>5</code>, then the next two statements are equivalent:</p> <pre><code>var myVal = bar * 100; // use 'bar' var myVal = 5 * 100; // don't use 'bar' </code></pre> <p>Well, if you can use <code>5</code> on its own, why can't you use <code>function() {\*code*\}</code> on its own too? In fact, you can. And that's called an anonymous function. So these two examples are equivalent as well:</p> <pre><code>var foo = function() {/*code*/}; // use 'foo' foo(); (function(){/*code*/}()); // don't use 'foo' </code></pre> <p>The only difference you should see is in the extra brackets. That's simply because if you start a line with the keyword <code>function</code>, the parser will think you are declaring a function using the very first pattern at the top of this answer and throw a syntax error exception. So wrap your entire anonymous function inside a pair of braces and the problem goes away. </p> <p>In other words, the following three statements are valid:</p> <pre><code>5; // pointless and stupid 'some string'; // pointless and stupid (function(){/*code*/}()); // wonderfully powerful </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload