Search code examples
javascriptorder-of-execution

Javascript variable declaration in head vs body


Is there a difference between declaring a variable in the head and using it in the body like so....

       <head>
          <script>
             var girlFriendName = "Jennifer Lawrence";
           </script>
       </head>
        <body>
            <script>
             console.log("I wish my girlfriend was " + girlFriendName);
           </script>
        </body>

And declaring it and using it in the body like so..

          <body>
           <script>
             var girlFriendName = "Jennifer Lawrence";
           </script>
            <script>
             console.log("I wish my girlfriend was " + girlFriendName);
           </script>
         </body>

Is there ever a case when you might want to declare them in the head as opposed to the body?


Solution

  • From a functional point of view there is no difference. It is just recommended to put the JS in (at the end of) the body.

    This is a good practise because it's more userfriendly. First the entire DOM and CSS will be loaded, which will result in the page being displayed as soon as possible. If loading your javascript takes a lot of time, then the actual displaying might be postponed or blocked, and the page might change in a shocking fashion. Originally javascript didn't influence the layout of the page, so it doesn't matter if it was loaded a bit later.