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?
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.
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){
.
The wrapping function is called an anonymous (it has no name and it isn't assigned to a variable) self-executing (it executes immediately, by itself) function.
I don't remember seeing an exact name for this pattern, but it prevents variable from leaking into global scope.