The script tag is used when we want to put a JavaScript code in an HTML file.

The script is the HTML element tag used to insert a JavaScript code in an HTML file. It is also used to link an external JavaScript file to the HTML file.

A code example

Here is a code example of how a script tag is used to add JavaScript inside the HTML file.

<!DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Example site</title>
  </head>
  <body>
    <h1 id="exampleText">This text will turn into red color.</h1>
    <button onclick="turnRed()">Red</button>

    <script>
      function turnRed() {
        document.getElementById("exampleText").style.color = "red";
      }
    </script>
  </body>
</html>

In the code above, we make a simple JavaScript program that will change the text color into red when we click the button.

Notice how the JavaScript code is inserted between the opening <script> tag and the closing </script> tag. This will ensure that the code will work correctly in an HTML file.

You can insert the script tag at the top or bottom of the body tag. It is recommended to insert the script tag at the bottom of the body tag as this will help improve the load speed of the web page.

Get my free e-book to prepare for the technical interview or start to Learn Full-Stack JavaScript