Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>On the most basic level, the <code>return</code> keyword defines what a function should return. So if I have this function:</p> <pre><code>function foo() { return 4; } </code></pre> <p>And then call it:</p> <pre><code>var bar = foo(); </code></pre> <p><code>foo()</code> will return <code>4</code>, hence now the value of <code>bar</code> is also <code>4</code>.</p> <p>Onto your specific example:</p> <p>In this use case the <code>return</code> is used to basically limit outside access to variables inside the <code>hash</code> variable.</p> <p>Any function written like so:</p> <pre><code>(function() {...})(); </code></pre> <p>Is self-invoking, which means it runs immediately. By setting the value of <code>hash</code> to a self-invoking function, it means that code gets run as soon as it can.</p> <p>That function then returns the following:</p> <pre><code>return { contains: function(key) { return keys[key] === true; }, add: function(key) { if (keys[key] !== true){ keys[key] = true; } } }; </code></pre> <p>This means we have access to both the <code>contains</code> and <code>add</code> function like so:</p> <pre><code>hash.contains(key); hash.add(key); </code></pre> <p>Inside <code>hash</code>, there is also a variable <code>keys</code> but this is not returned by the self-invoking function that <code>hash</code> is set to, hence we cannot access <code>key</code> outside of <code>hash</code>, so this wouldn't work:</p> <pre><code>hash.keys //would give undefined </code></pre> <p>It's essentially a way of structuring code that can be used to create private variables through the use of JavaScript closures. Have a look at this post for more information: <a href="http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-private-variables-in-javascript/" rel="noreferrer">http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-private-variables-in-javascript/</a></p> <p>Hope this Helps :)</p> <p>Jack.</p>
 

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