Before you can run any JavaScript in a browser, it has to be connected to an HTML page. There are three ways to do that — writing it directly inside the page, linking to a separate file, or (rarely, these days) putting it inline on an element itself. Knowing where and how to place your scripts also affects how fast your page loads and whether your JavaScript can actually find the elements it needs to work with.

Inline JavaScript with the script Tag

The simplest way is to write JavaScript directly inside a <script> tag in your HTML file:

<!DOCTYPE html>
<html>
<body>
  <h1>Hello Page</h1>

  <script>
    console.log("This script runs as soon as the browser reaches it");
  </script>
</body>
</html>

This works fine for small demos, but for any real project you'll want your JavaScript in its own file, separate from your markup.

Linking an External JavaScript File

Create a separate .js file and reference it with the src attribute:

<!-- index.html -->
<script src="script.js"></script>
// script.js
console.log("Loaded from an external file");

External files are easier to maintain, can be cached by the browser across page loads, and keep your HTML readable instead of cluttered with logic.

Where to Place Your Script Tag

If you put a <script> tag in the <head> without any extra attributes, it will try to run before the rest of the page has loaded — which means any JavaScript trying to find an element with document.querySelector(...) might fail, because that element doesn't exist in the DOM yet. Two common fixes:

<!-- Option 1: place the script at the very end of <body>, after all HTML -->
<body>
  ...page content...
  <script src="script.js"></script>
</body>

<!-- Option 2: keep it in <head>, but defer it until the HTML is parsed -->
<head>
  <script src="script.js" defer></script>
</head>

defer tells the browser to download the script in the background but wait to run it until the HTML document is fully parsed, in the order the scripts appear. async is similar but runs the script as soon as it finishes downloading, with no guaranteed order relative to other scripts — useful for independent scripts like analytics, but risky if your script depends on the DOM or another script's variables.

Once your script is wired up correctly, the natural next step is learning how to store data with JavaScript variables.