3

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>
Abe Miessler
  • 82,532
  • 99
  • 305
  • 486

5 Answers5

2

It's often used to ensure all variables used in the code take their values from this snippet of code only - local scope. They ignore variables defined outside of the snippet.

var a = 10;
(function() {
    alert(a); // undefined
    var a = 5;
    alert(a); // 5
    })();

Its other main use is to ensure code will work in one Javascript library (eg. jQuery) even when there are multiple libraries (eg. Prototype, Mootools) being used on the page. You'd do something like...

(function($) {
    alert('test');
    // You can now use the jQuery $ in here
    // And not worry about the Prototype $ being used instead
    })(jQuery);

By passing the jQuery object into the function, it gets the local-scope variable name of $, which will take precedence over the global-scoped Prototype $ (which has completely different methods available).

Joe
  • 15,669
  • 4
  • 48
  • 83
  • While that's used by most jQuery plugins, this is **far from being the main usage of this pattern**. – Arnaud Le Blanc Sep 11 '11 at 16:46
  • Updated to fix that, my bad :) – Joe Sep 11 '11 at 16:49
  • 1
    "They ignore variables defined outside of the snippet." is wrong. Try taking away the second `var a = 5`. This is a side effect of the fact that in JS all the var declarations are implicitly moved at the beginning of the function (and it's the reason why JSLint gives a warning for code similar to that) – xanatos Sep 11 '11 at 16:54
2

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:

(function() {

    var counter = 0;

    $('#elem').click(function() {
         counter += 1;
         alert('#elem has been clicked ' + counter + ' times!');
    });

}());

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

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
1

In this case, yes. But.

Putting code inside of a function, then immediately executing it, is one way to isolate variables, since JavaScript really only has two scopes, global and function. If there was a variable defined before the alert, say, keeping it all within another function creates a new scope, preventing trashing a global variable with the same name.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
1

In this case, it doesn't do much. alert("test") will run no matter what and won't be reused.

But more generally, by wrapping your JavaScript (often an entire file) in an anonymous function, you can prevent your variables and functions from polluting the global scope, which is helpful to avoid conflicts with other code.

More info here

Community
  • 1
  • 1
brymck
  • 7,555
  • 28
  • 31
0

Here I have shown you why you have the option of a function with an alert. I wanted people to know when they click my button they can only click it once so i added an alert. The function is what I am creating (a button which adds a vote & then displays no. of votes) and the alert is just an addition.

<!DOCTYPE html>
<html>

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Vote!</title>


<script type="text/javascript">

function countClicks() {
var x = 0;


x += 1
document.getElementById( "counting" ).innerHTML = x;

var clickLimit = 1; //Max number of clicks
if(x>=clickLimit) {

 alert('you can only click once')
            }
else
{
    ClickCount++;
    return true;
}
}

</script>

</head>
<body>

<div style="margin-left:100px;">
<input type="button" value="VOTE" name="clickOnce" onclick="return countClicks();" />
<div id="counting"></div>
</body>

</html>
user939222
  • 17
  • 3