0

There is the following code snippet included in the FOSS web-based application:

<script type="text/javascript">
  (function() {
    // code follows
    // ...

  })();
</script>

As you can see, the function definition is surrounded by an extra pair of brackets, also followed by another pair of brackets. There is no jQuery or any other JS framework used in the application. The function is not referenced/called later in the script.

Question: What will these characters ( (very first character of the javascript code and )(); (the last four characters of the js code) cause? And (more importantly) why?

Thanks in advance for the explanation.

PS: English is not my first language, please take into consideration.

user5265
  • 11
  • 4
  • 2
    its an immediately invoked function expression (IIFE), possible duplicate of [http://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript](http://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) – riteshtch Oct 28 '16 at 03:03
  • It's a self invoked function http://www.w3schools.com/js/js_function_definition.asp – Jeremy Jackson Oct 28 '16 at 03:03
  • Welcome to StackOverflow! The question is already answered, see the linked question. – Tushar Oct 28 '16 at 03:03
  • Thank you guys for immediate & useful help. If `Tushar` and `ritesht93` would write your comment as an answer, I would accept it as the solution. This is what I was searching for. Thanks again! – user5265 Oct 28 '16 at 03:12

1 Answers1

0

This is called a closure. It is a self executing function and it means that you can define as many variables as you need without polluting the window namespace.

Adrian Brand
  • 15,308
  • 3
  • 24
  • 46