Thuta Learning
JavaScript
BasicProgrammingBeginner

JS Intro

JavaScriptLesson 220 min

What you'll walk away with

  • Describe the separate jobs of HTML, CSS and JavaScript on one page
  • Explain the event-driven pattern: listen now, react later
  • Load JavaScript into a page with a <script> tag (using defer) or an external file
  • Name four common jobs of JavaScript: interactivity, DOM updates, talking to servers and Node.js back ends

Explain it simply

Explain it simply

Think of a web page as a house. HTML is the walls and rooms, CSS is the paint and furniture, and JavaScript is the electricity that makes a light come on when someone presses a switch.

Without JavaScript the page can only show what was written in advance. With it, the page can react: count likes, check a form before it is sent, load new posts as you scroll, or show a different greeting depending on the time of day.

Problem → Why → Solution

The problem: HTML alone cannot react to a click

Picture a shop page with an "Add to cart" button and a count of items in the cart. With only HTML and CSS the button looks fine, but clicking it does nothing and the count stays at 0. Before JavaScript, sites had to reload the whole page from the server for every click like this.

cart.html
<!-- cart.html: nothing is listening for the click -->
<p>Items in cart: 0</p>
<button>Add to cart</button>

<!-- Click the button: the page stays exactly the same -->

Why is JavaScript needed?

HTML describes content and CSS describes appearance; neither can remember a changing number or run steps when something happens. You need a language that keeps state (the count), listens for events (the click) and updates the page. JavaScript was created at Netscape in 1995 for exactly this job, and apart from WebAssembly it is still the only programming language browsers run directly.

Core concept: listen now, react later

A page is built from three layers. HTML says what is there (headings, paragraphs, buttons), CSS says how it looks (colours, spacing, layout), and JavaScript says how it behaves (what changes when something happens). Keeping the layers separate means you can restyle a page without touching its logic, and fix logic without touching its content.

Most JavaScript in a page does not run top to bottom and stop. It runs once to set things up, finding elements and registering listener functions, and then it waits. When the user clicks, types or scrolls, the browser fires an event and calls the function you registered. This listen-now, react-later pattern is the heart of interactive pages, and Node.js uses the same idea for incoming network requests.

As a language, JavaScript is high-level and dynamically typed: you do not declare types, and one variable can hold any kind of value. A garbage collector frees memory for you. JavaScript is also single-threaded, so only one piece of your code runs at a time. Slow work such as a network request is handed to the host and resumed later through callbacks or promises, which the Async chapter covers in detail.

JavaScript needs no separate compile step. The browser or Node.js accepts the source code directly, and the engine compiles frequently used parts into machine code while the program runs (JIT compilation). That is why saving a file and refreshing the page is enough to see your change.

JobExample
Interactive front endResponding to clicks and form input
DOM manipulationChanging HTML content and CSS classes while the page runs
Talking to serversLoading data in the background with fetch() (once called AJAX)
Back endWriting APIs and servers with Node.js
Mental model: a tiny event cycle
  1. Setup code runs once
  2. A listener function is registered
  3. A user action fires an event
  4. The listener runs and updates the page

addEventListener does not run the function; it stores it to be called when the event arrives.

General pattern: an event listener

javascript
// 1. get the thing that produces events
const target = getEventSource();

// 2. register what should happen later
target.addEventListener("eventName", () => {
  // react: update state, print, change the page
});

In a browser, target is usually an element such as document.querySelector("button"). addEventListener takes the event name as a string and a function, the function itself rather than the result of calling it.

Example: simulating clicks in Node.js

The event system that browser buttons use is called EventTarget, and Node.js has it built in too. That lets you watch the listen-then-react pattern in a terminal without any page. dispatchEvent() plays the role of a user's click. Before running it, predict the order of the four lines: which one comes first?

events.js
// The same idea a browser button uses: listen first, react later.
const button = new EventTarget();
let clicks = 0;

button.addEventListener("click", () => {
  clicks = clicks + 1;
  console.log(`Button clicked ${clicks} time(s)`);
});

console.log("Page loaded, waiting for clicks...");
button.dispatchEvent(new Event("click"));
button.dispatchEvent(new Event("click"));
console.log("JavaScript is running!");

Code breakdown

  1. Line 2const button = new EventTarget();

    Creates an object that can produce events. Every button element in a browser is a kind of EventTarget too.

  2. Line 3let clicks = 0;

    This is the page's state, the changing number HTML could not remember. It is declared with let because it will change.

  3. Lines 5-8button.addEventListener("click", () => {

    Registers the arrow function () => { ... } for the "click" event. Nothing inside the body runs at this point, which is why the first output line is "Page loaded...".

  4. Line 11button.dispatchEvent(new Event("click"));

    Fires a click event. The listener runs right away, adds 1 to clicks and prints its message. It is called twice, so the count reaches 2.

  5. Line 13console.log("JavaScript is running!");

    A simple message confirming that the script ran. It prints after both events because dispatchEvent is synchronous in this simulation.

You should see
Page loaded, waiting for clicks...
Button clicked 1 time(s)
Button clicked 2 time(s)
JavaScript is running!

Putting JavaScript into a page

In a browser, JavaScript goes into a <script> tag. On the page below, clicking the button changes the paragraph's text. The script sits at the end of the body, so the elements already exist when it runs. It sets the text with textContent rather than innerHTML: for plain text, textContent is safer because it is never interpreted as HTML.

index.html
<!DOCTYPE html>
<html>
  <body>
    <p id="demo">Waiting...</p>
    <button id="hello">Say hello</button>

    <script>
      function sayHello() {
        document.getElementById("demo").textContent = "Hello, JavaScript!";
      }
      document.getElementById("hello").addEventListener("click", sayHello);
    </script>
  </body>
</html>

As a project grows, move the code into its own file such as app.js and write <script src="app.js" defer></script> in the <head>. defer runs the script only after the whole HTML is parsed, so looking up elements no longer returns null.

In real projects

Where this shows up in real projects

A sign-up form that warns about a short password while you type, a social feed that loads more posts when you reach the bottom, a map that moves when you drag it: all of these are JavaScript listeners reacting to events. Single-page apps such as Gmail never fully reload; JavaScript fetches data and redraws only the part that changed.

On the server, Node.js handles thousands of requests with the same event pattern: each incoming request calls a handler function, and while it waits for a database answer it keeps accepting other requests. That is why Node.js is popular for chat apps, APIs and other services that mostly wait on input and output.

Common mistakes

Common mistakes

1. Running the script before the element exists

A script in the <head> without defer runs before the browser has read the body. document.getElementById("demo") returns null and the next line throws TypeError: Cannot set properties of null. Add defer, or move the script to the end of the body.

2. Calling the function instead of passing it

addEventListener("click", sayHello()) runs sayHello immediately while the page loads and registers its return value, undefined, as the listener, so clicks do nothing. Pass sayHello without the parentheses.

3. Putting user text into innerHTML

Writing comment-box text with element.innerHTML = text lets someone type HTML such as <img onerror=...> and run code on your page (XSS). Use textContent for plain text.

Best practices

Best practices

  • Keep JavaScript in .js files loaded with defer instead of onclick attributes scattered through the HTML, so all behaviour lives in one place.
  • Use textContent for text and keep innerHTML for trusted HTML you wrote yourself.
  • Open the DevTools console whenever a page misbehaves; most JavaScript errors appear there with a file name and line number.

Mini challenge

Mini challenge: a like button

Use EventTarget to simulate a like button in Node.js that reacts to "like" and "unlike" events.

  • Each "like" event adds 1 to likes and prints Likes: <n>
  • Each "unlike" event subtracts 1, but likes never goes below 0
  • Dispatch five events in this order: like, like, unlike, unlike, unlike
like-button.js
const likeButton = new EventTarget();
let likes = 0;

// TODO: listen for "like": add 1, then print "Likes: <n>"

// TODO: listen for "unlike": subtract 1 without going below 0, then print

// TODO: dispatch like, like, unlike, unlike, unlike

Expected: Five lines are printed: Likes: 1 Likes: 2 Likes: 1 Likes: 0 Likes: 0

Show hint

Math.max(0, likes - 1) gives 0 whenever the result would be negative. Create each event with new Event("like") and pass it to likeButton.dispatchEvent().

Show solution
like-button.js
const likeButton = new EventTarget();
let likes = 0;

likeButton.addEventListener("like", () => {
  likes = likes + 1;
  console.log(`Likes: ${likes}`);
});

likeButton.addEventListener("unlike", () => {
  likes = Math.max(0, likes - 1);
  console.log(`Likes: ${likes}`);
});

likeButton.dispatchEvent(new Event("like"));
likeButton.dispatchEvent(new Event("like"));
likeButton.dispatchEvent(new Event("unlike"));
likeButton.dispatchEvent(new Event("unlike"));
likeButton.dispatchEvent(new Event("unlike"));

Quick quiz 1 / 3

In the example, addEventListener comes first in the code. Why does "Page loaded, waiting for clicks..." still print first?

Quick quiz 2 / 3

What is wrong with button.addEventListener("click", sayHello());?

Quick quiz 3 / 3

A <script> in the <head> without defer runs document.getElementById("demo") for a <p id="demo"> further down the body. What does it return?

What to remember

  • HTML owns content, CSS owns appearance and JavaScript owns behaviour.
  • Page code runs once to set up, registers listeners, and reacts when events arrive.
  • Put <script> at the end of the body, or in the <head> with defer.
  • JavaScript is dynamically typed and single-threaded, and it runs on servers through Node.js.

MDN — JavaScript Guide — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

JS Intro | Thuta Learning