I would like to know what this means:
(function () {
})();
Is this basically saying document.onload?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created.
It has nothing to do with any event-handler for any events (such as
document.onload).Consider the part within the first pair of parentheses:
(function(){})();….it is a regular function expression. Then look at the last pair(function(){})();, this is normally added to an expression to call a function; in this case, our prior expression.This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.
This is why, maybe, you confused this construction with an event-handler for
window.onload, because it’s often used as this:Correction suggested by Guffa:
Update
Since this is a pretty popular topic, it’s worth mentioning that IIFE’s can also be written with ES6’s arrow function (like Gajus has pointed out in a comment) :