Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do many javascript libraries begin with "(function () {"?

Tags:

javascript

Why do many javascript libraries look like this:

(function () { 
    /* code goes here */ 
})();

It appears to define an unnamed function which is immediately called. Why go through this effort?

like image 525
Steve Hanov Avatar asked Dec 24 '09 13:12

Steve Hanov


People also ask

What is function () () in JavaScript?

A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.

Why do we use functions in JavaScript?

In JavaScript, a function allows you to define a block of code, give it a name and then execute it as many times as you want. A JavaScript function can be defined using function keyword.

What is require () in JavaScript?

require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object. require() statement not only allows to add built-in core NodeJS modules but also community-based and local modules.

How many functions are there in JavaScript?

There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.


1 Answers

This is standard way to do namespacing in JavaScript. If you just declare

var my_cool_variable = 5;

it will be global and might conflict with other libraries, that use the same variable.

However, if you do

(function() {
    var my_cool_variable = 5;
})();

it is now local variable for anonymous function and is not visible outside of the scope of that function. You still can expose accessible API by not stating var in front of variable, that way it will be global but now you have a choice.

like image 136
vava Avatar answered Sep 17 '22 13:09

vava