JavaScript from Zero: Variables, the DOM, and Making Buttons Do Things
What JavaScript actually does in a browser, how const and let store values, and how to wire a button click to change your HTML live.
You'll learn how JavaScript attaches to an HTML page, how const and let store changing values, and how to find an HTML element and update it when a user clicks a button. Zero programming experience required.
1. HTML is the noun, CSS is the adjective, JavaScript is the verb
HTML puts a <button>Click me</button> on the page. CSS paints it hot pink. Neither of them can make anything happen when a human actually clicks it.
JavaScript is the programming language built into every web browser. It listens for things—clicks, keystrokes, form submissions, timers—and reacts by changing the page live, without reloading.
To add JavaScript to index.html, create a file called app.js in the same folder and link it in <head> with the defer attribute:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Interactive Page</title>
<script src="app.js" defer></script>
</head>
<body>
<h1 id="headline">Gerald's Mood</h1>
<p id="status">Mildly caffeinated.</p>
<button id="coffee-btn" type="button">Drink coffee (0)</button>
</body>
</html>Why defer? Because browsers read HTML from top to bottom. Without defer, <script> runs while still in <head>, before <body> even exists—so JavaScript looks for #coffee-btn, finds nothing, and crashes. defer tells the browser: "Download app.js now, but wait until the HTML is finished before running it."
2. Storing values with const and let
A variable is a name tag attached to a value in memory. JavaScript gives you two keywords for making them:
const— for a name tag you will not reassign to a new value.let— for a name tag whose value will change later (like a score or a click counter).
const name = "Gerald";
let coffees = 0;
coffees = coffees + 1;
console.log(name, "has had", coffees, "coffee");console.log(...) prints messages to the browser's secret developer diary. Right-click your page, click Inspect, and open the Console tab to see it:
Gerald has had 1 coffeeIf you try to reassign a const (name = "Bob"), JavaScript throws TypeError: Assignment to constant variable. Use const by default, and switch to let only when a variable needs to be reassigned.
3. Finding elements in the DOM
When the browser loads your HTML, it builds a live tree of JavaScript objects representing every tag on the page. That live tree is called the DOM (Document Object Model).
To grab an element from the DOM, call document.querySelector(...) using the exact same CSS selector syntax you already know (#id or .class):
const statusText = document.querySelector("#status");
const button = document.querySelector("#coffee-btn");
statusText.textContent = "Dangerous levels of optimism.";Refresh the page and <p id="status"> immediately reads Dangerous levels of optimism.—even though your index.html still says Mildly caffeinated.
Always use .textContent instead of .innerHTML when updating text. .textContent treats your string as literal text, whereas .innerHTML parses it as HTML—which is how attackers sneak <script> tags into pages if user input ends up there.
Change #headline in app.js using document.querySelector("#headline").textContent = "..." and verify it updates when you refresh the browser.
4. Reacting to clicks with addEventListener
Right now app.js changes the text the instant the page loads. To wait for a user click, attach an event listener:
const statusText = document.querySelector("#status");
const button = document.querySelector("#coffee-btn");
let coffees = 0;
button.addEventListener("click", () => {
coffees += 1;
button.textContent = `Drink coffee (${coffees})`;
if (coffees >= 5) {
statusText.textContent = "Gerald can now hear colors.";
} else {
statusText.textContent = `Cups consumed: ${coffees}`;
}
});Notice the backticks `...` (next to the 1 key). In JavaScript, backtick strings let you drop variables straight inside ${...}—far cleaner than gluing strings together with +.
And notice () => { ... }: that is a function wrapped up and handed to addEventListener, saying "Don't run this code now; run it every time the user clicks button."
Common mistakes
| Error / Bug | What it means | Fix |
|---|---|---|
TypeError: Cannot set properties of null | querySelector found nothing (typo in #id, or missing defer) | Check the selector spelling and add defer to <script> |
TypeError: Assignment to constant variable | Tried to change a const variable | Change const to let |
| Click handler runs once on load and never on click | Wrote addEventListener("click", myFn()) with () | Pass myFn without (), or wrap in () => myFn() |
| Nothing prints on the page | Used console.log() instead of updating .textContent | console.log only writes to DevTools Console |
Practice
- What does
const score = 10; score += 5;throw? - Why does
<script src="app.js"></script>inside<head>withoutdeferreturnnullfromdocument.querySelector("#coffee-btn")?
Answers:
TypeError: Assignment to constant variable.(scoremust be declared withlet).- Because
<head>runs before the browser has parsed<body>, so#coffee-btndoes not exist in the DOM yet.
What you learned
<script src="app.js" defer>loads JavaScript after the HTML is parsed.- Use
constby default andletwhen a variable needs to be reassigned. document.querySelector(...)grabs elements from the DOM using CSS selectors, and.textContentupdates their text safely.addEventListener("click", () => { ... })runs your code every time a user interacts with an element.