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: 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.
| Job | Example |
|---|---|
| Interactive front end | Responding to clicks and form input |
| DOM manipulation | Changing HTML content and CSS classes while the page runs |
| Talking to servers | Loading data in the background with fetch() (once called AJAX) |
| Back end | Writing APIs and servers with Node.js |
- Setup code runs once
- A listener function is registered
- A user action fires an event
- 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
// 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?
// 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
- Line 2
const button = new EventTarget();Creates an object that can produce events. Every button element in a browser is a kind of EventTarget too.
- Line 3
let clicks = 0;This is the page's state, the changing number HTML could not remember. It is declared with let because it will change.
- Lines 5-8
button.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...".
- Line 11
button.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.
- Line 13
console.log("JavaScript is running!");A simple message confirming that the script ran. It prints after both events because dispatchEvent is synchronous in this simulation.
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.
<!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
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, unlikeExpected: 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
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
Quick quiz 2 / 3
Quick quiz 3 / 3
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