Where do we put JavaScript code in the HTML code;

JavaScript can be connected to the HTML file using three different ways:

  • Write your JavaScript at the head of the HTML document
  • Write your JavaScript at the end of the body of the HTML document
  • Use an external sheet and reference your JavaScript either at the head or at the end of the body of the HTML document
In the HTML file

When we use the first or the second way, we need to wrap our code inside script tags, <script>.. </script>.

In general, when we write our JavaScript directly at the HTML is preferable to put it at the end of the body rather than at the head. This is because we want our page to have completed the loading so the JavaScript can function properly.

<!DOCTYPE html>
<html>
  <head>
        . . . <script> load JavaScript libraries here </script>. . .
  </head>
  <body>
        . . . <script> your JavaScript code typically goes at the end of body </script>. . .
  </body>
</html>

External file

When we use an external script file we do NOT include the script tags in the content of the script file. We just write our JavaScript. Again we prefer to reference our JavaScript just before the closing HTML body tag.

Our external JS script file /js/myscript.js:

console.log("Hello World");
// Some JavaScript code in here without the use of <script> tags


Our HTML file index.html:

<!DOCTYPE html>
<html>
  <head>
        . . . <script> load JavaScript libraries here </script>. . .
  </head>
  <body>
        . . . <script type="text/javascript" src="js/myscript.js"></script>. . .
  </body>
</html>

Over the three available ways, the 3rd one, usage of an external script file, is the preferable way.
One reason for this is because, this way, we separate markup from code. Moreover, it is easier to read the files and do changes. Also, it helps the page to load more quickly and we can share the same script file across multiple HTML files.

For more information: https://www.w3schools.com/js/js_whereto.asp