I came across the following javascript:
<body>
<script type="text/javascript">
(function() {
alert('test');
})();
</script>
And I was curious what the purpose of having the code inside of a function is? Wouldn’t this do the same thing if it were just written like this:
<body>
<script type="text/javascript">
alert('test');
</script>
Usually this is used to create a private scope, and to not pollute the global scope. In this case, however, there is no benefit.
Example:
Here the counter variable is private to the code inside of the enclosing function. The other functions defined in the enclosing function have access to those variables (they close the variables; they are closures).
This is usually called an Immediately Invoked Function Expression