Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this practice called in JavaScript?

When you wrap your JavaScript code in a function like this:

(function(){

  var field = ...;
  function doSomthing(){...
  ...


})();

I noticed that this fixes scoping problems for me on a lot of web pages. What is this practice called?

like image 555
stevebot Avatar asked Sep 15 '10 17:09

stevebot


People also ask

How is the function called in JavaScript?

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body.

What is an anonymous function in JavaScript?

Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.

How do you check if a function is executed in JavaScript?

Using the typeof Operator In JavaScript, the typeof operator is useful to check the type of the variable, function, objects, etc. When we use the function name as the operand of the typeof variable, it returns the 'function' string, and we can check whether the function is defined.


2 Answers

The pattern is called self-invocation, a self-invoking function. It can create a closure, but that is an effect of the pattern (perhaps the intended effect), not the pattern itself.

like image 138
palswim Avatar answered Oct 29 '22 01:10

palswim


To clarify a bit for the comments below, most of the time it's creating a closure, it keeps your variables scoped to that local closure, as to not create global variables, it both keeps things clean and avoids any potential unwanted changes to those variables.

There are some excellent answers here that explain the why a bit more: How does a javascript closure work?

It's only a creating closure when something inside that scope is exposed to an outer scope, which is usually the case, but I can't be sure for your example without seeing more code. If nothing is exposed then no closure's created...otherwise it's just an anonymous function executing immediately.

The })(); format at the end, as opposed to }); is actually calling that closure to execute immediately, with no parameters. If you had something in it, for example })(something); then that something would be passed as the first argument here: (function(somethingParam){.

like image 20
Nick Craver Avatar answered Oct 29 '22 00:10

Nick Craver