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. A little bit of googling resulted in something unbelievably simple like this:
(function() {
alert('Hello world!');
})();
If you need you can pass arguments as you’d normally do:
(function( arg ) {
alert('Hello world! '+arg);
})(9999);
Quick and simple
