Skip to content

JavaScript Tutorial Getting Started

How JavaScript Works in a Browser

Lesson 4 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

Here is what happens, step by step, when you open a page that uses JavaScript.

  1. The browser downloads the HTML and starts reading it from top to bottom.
  2. When it reaches a <script>, it gets the code (from the page or a file).
  3. The browser’s JavaScript engine reads the code and runs it.
  4. Your code can change the page through the DOM, a live model of the page that the browser builds from the HTML.
  5. When the user clicks, types or scrolls, the browser creates an event, and your code can respond.

Your code runs one thing at a time

JavaScript runs on a single line of work, the main thread, and does one task at a time. While it is busy, the page cannot respond. That is why a long calculation can make a page freeze, and why code that waits for something (a server reply, a timer) does not block everything. You will see how in Synchronous vs Asynchronous.

The page is not the same as the file

The HTML file never changes. What changes is the DOM in memory, which is what the screen shows.

index.html
HTML
<h1 id="title">Original title</h1>

<script>
  console.log("Script is running");
  document.querySelector("#title").textContent = "Changed by JavaScript";
</script>

Open the Result and look at the heading. The source code still says “Original title”, but the page shows the new text.

Code that waits for events

Most browser JavaScript sits quietly until something happens.

index.html
HTML
<input id="name" placeholder="Type your name">
<p id="out"></p>
<script>
  const input = document.querySelector("#name");
  input.addEventListener("input", () => {
    document.querySelector("#out").textContent = "Hello, " + input.value;
  });
</script>

Nothing runs when you press Run, apart from setting up the listener. The function inside runs every time you type.

info
Order matters
A script that runs before the elements it needs exist will fail to find them. The next lesson shows where to place scripts and how defer helps.