Search code examples
javascriptonloadmodule-pattern

JavaScript Module Pattern(function(){})(); vs block statement


I saw an answer to some question earlier that used my "Weird" example, and I was wondering if there was any benefit to either method.

Some HTML:

<span id="them">Hey</span>
<span id="me">Hey</span>

What is the difference between:

(function()//doing this
{
    them.innerHTML = "Weird<br>";
})();

me.innerHTML = "Not so weird<br>";//and doing this

And even, why do people use window.onload when they can put scripts at the bottom of the body? Or is it just a matter of personal preference?


Solution

    • Your first code snippet: is a Module Pattern Or Immediately Invoked Function Expression(IIFE)

      (function()//doing this
      {
          them.innerHTML = "Weird<br>";
      })();
      
    • This when encountered by the Javascript compiler will immediately invoke the function when it encounters (); and keeps the variables and functions within its scope.

      You must read Java-script Design Patterns to better understand its use and benefits.

    • Second code snippet: is just a JavaScript statement.

      me.innerHTML = "Not so weird<br>";//and doing this
      

      This when encountered by the JavaScript compiler will immediately execute it.

    Remember both snippets executions depends on where its placed.

    • So, to answer your other question. window.onload is an event fired when the HTML DOM is fully loaded and browser can read all its elements.