vote up 0 vote down star

Possible Duplicate:
JavaScript scope and closure

Why should I (or shouldn't I) do this...

<script type="text/javascript">
  (function() {
    alert("Test");
  })();
</script>

Instead of this...

<script type="text/javascript">
  alert("Test");
</script>

What is the first approach called, and what are the benefits/drawbacks? I assume this has something to do with the execution, but I'd like to know more.

flag

77% accept rate

closed as exact duplicate by Crescent Fresh, insin, seth, Hank Gay, CMS Sep 1 at 16:56

This question covers exactly the same ground as earlier questions on this topic; its answers may be merged with another identical question.

1 Answer

vote up 9 vote down

Scope/namespace control. JavaScript only has two scopes: global and function. One of the biggest problems you will encounter when using lots of javascript on a page is namespace conflicts in the global scope.

So the only way to create a new scope is to use a function. So the pattern of creating/calling an anonymous function is a decent way to "fake" lexical scoping. This way have immediate execution, but do so without polluting the global namespace.

<script type="text/javascript">
  var i = 0; // i is in the global scope.  This is bad.
</script>

compared to

<script type="text/javascript">
  (function() {
    var i = 0; // i is visible only to this anonymous function. This is good.
  })();
</script>
link|flag
Just for the record, JavaScript 1.7 introduced local scoping through the let statement... is.gd/2Lw8x – CMS Sep 1 at 17:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.