-1

I came across something like this while I was looking at preexisting JavaScript code. So I tried to write similar code and it worked correctly (or rather I don't know if its working correctly or not)

The code is like this

//main.js
(function() {
    alert("am I being called?");
})();

I included this main.js in my index.html and as soon as I refreshed the page, the alert popped up.

What is this?

and what JavaScript concepts/features do I need to study to correctly understand this?

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
AdityaParab
  • 7,024
  • 3
  • 27
  • 40

1 Answers1

2
(function () {
    ...
})();

is known as an Immediately-Invoked Function Expression. IIFEs are often used to provide a scope for variables and functions to reduce global namespace pollution.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367