/function, JavaScript

Self executing function in JavaScript

In my last project I needed a function in JavaScript that will execute itself as soon as it’s ready. My first idea was something like that:

// declare function
function myFunction() {
  alert('Hello world!');
}
// run it when DOM is ready with help of jQuery
$(document).ready(function() {
  myFunction();
});

but in the back of my mind I knew there is a better way, without any dependancies. A little bit of googling resulted in something unbelievably simple like this:

(function() {
  alert('Hello world!');
})();

If you want, you can pass arguments as you’d normally do:

(function( arg ) {
  alert('Hello world! '+arg);
})(9999);
// result: "Hello world! 9999"

Quick and simple 🙂