Choose a step
Your first click
Press the button. Watch what changes.
Here JavaScript has one clear job: wait for a click and change a sentence on the page. Before clicking, you will read “No clicks yet.”; afterwards, “You pressed the button!”. Try it and watch the response.
The button and sentence are HTML elements. JavaScript connects the action on the button to the change in the sentence. In the next steps, you will use the same idea to count clicks, choose a response and read a name entered on the page.
No clicks yet.
To make this example yourself, you need a browser and a code editor such as Visual Studio Code: edit the files, save and check the result in the browser. If HTML buttons and attributes are still unfamiliar, start with the HTML guide.
Follow the project through the Reset button. Then use the final sections when you want to explore more of the language. If the button here is unavailable, the examples and instructions in the chapters remain readable.
Bring the first click into your files
Create a folder named js-practice and open it in your editor. Create index.html and script.js inside it. Write this in index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My first JavaScript experiment</title>
<script src="script.js" defer></script>
</head>
<body>
<h1>My first experiment</h1>
<button id="button" type="button">Show message</button>
<p id="result" aria-live="polite">No clicks yet.</p>
</body>
</html>Write this in script.js:
const button = document.querySelector("#button");
const result = document.querySelector("#result");
button.addEventListener("click", () => {
result.textContent = "You pressed the button!";
});Save both files and open index.html in a browser. Before clicking, you see “No clicks yet.”; after clicking, you see “You pressed the button!”. Change the quoted text in script.js, save and reload: the new message will appear on the next click.
src="script.js" points to the file in the same folder. defer runs this script after the browser has parsed the HTML: the button already exists when JavaScript looks for it. If nothing happens, check the filename and look for an error in the browser console.
Read the code behind the first click
script.js contains instructions: JavaScript reads them from top to bottom when the page opens. The first two lines look for the button and paragraph in the HTML. document represents the page; querySelector finds an element; #button means “the element with id="button"”. The quotes mark text used as a selector, rather than a variable name.
const button = document.querySelector("#button");
const result = document.querySelector("#result");const gives the found value a name. You can then use button and result without searching again. If the ID differs from the HTML, querySelector returns null, meaning “no element”. Temporarily change #result to #missing: the Console shows an error when you click. Restore the correct ID.
The addEventListener line tells the browser: “when a click arrives, run the instructions inside the braces”. The function in () => { ... } is code to run later. textContent changes the paragraph text. This changeable page structure is called the DOM. Loading the script does not display the new message yet: you must click.
Parentheses () pass data to a function; braces {} group instructions; = assigns a value; a dot accesses a property or function on an element. Here we use a semicolon to mark the end of an instruction. Read the earlier code again in this order: find the elements, wait for a click, change the text.
Read and update the page: the DOM
A page is more than the text written in HTML. When the browser reads it, it builds a structure of elements JavaScript can find and change: the DOM. document gives access to the page; querySelector returns the first element matching a CSS selector.
const title = document.querySelector("h1");
const result = document.querySelector("#result");
console.log(title.textContent);
result.textContent = "Message updated";textContent reads or replaces text. If a selector finds nothing, the result is null: check that an element exists before using its properties. To add elements, use createElement and append. For text typed by a user, prefer textContent; innerHTML interprets markup and can run unwanted HTML when given untrusted data. This guide does not need it to show a sentence.
The page has more tools than text
The DOM is the tree of elements the browser builds from HTML. querySelector returns the first element matching a CSS selector; querySelectorAll returns all matches in a collection you can loop over. If there is no match, the first method returns null.
const rows = document.querySelectorAll(".item");
rows.forEach((row) => {
row.classList.add("read");
});
const card = document.querySelector("[data-state]");
card.dataset.state = "complete";classList.add adds a class without removing the others; remove removes it and toggle switches it on or off. HTML attributes describe an element; dataset gives access to data-* attributes. To create an element, use document.createElement, set its textContent, and insert it with append. Avoid building markup from text entered by a user.
Before counting: what values does JavaScript use?
A value is a piece of data the program works with. "You pressed the button!" is text, called a string; 0 and 3 are numbers; true and false are boolean values for yes/no questions. === asks whether two values are equal and have the same type. Open the Console tab in your browser tools, paste one line at a time and press Enter. console.log displays a value in the tools without changing the page.
console.log("Clicks: " + 1); // Clicks: 1
console.log(1 + 1); // 2
console.log(1 === 1); // trueThe first line joins text and a number: the result is text. The second adds two numbers. The third asks whether the numbers are equal and returns a boolean. Text after // is a note for readers; JavaScript does not run it. typeof 1 shows "number", while typeof "1" shows "string": the digit looks alike, but its type changes what operations do.
Some values describe an absence. undefined often means a value has not been assigned; null is what querySelector returns when it finds no element. You do not need to memorise every type now: first recognise number, text, boolean and absence, because you will meet them in the counter.
Operators: calculate, compare, combine
An operator performs an operation on values. + adds numbers or joins strings; % returns a remainder; === compares value and type; >= compares size. Comparisons return a boolean: true or false.
const total = 4 + 3;
const remainder = 7 % 3;
const reachedGoal = total >= 7;
const canContinue = reachedGoal && true;
console.log(total, remainder, canContinue); // 7, 1, true&& requires both conditions to be true; || requires at least one; ! reverses a boolean. += updates a variable by adding a value: clicks += 1 is the same as clicks = clicks + 1. Parentheses make groups clear, for example (validName && reachedGoal) || specialAccess. Use them when a rule combines operators so the order remains readable.
Strings and template literals
A string is text surrounded by single quotes, double quotes, or backticks. To insert values into a message, template literals use backticks and ${...}:
const name = "Ada";
const clicks = 3;
const message = `Hi ${name}, you clicked ${clicks} times.`;
console.log(message); // Hi Ada, you clicked 3 times.Inside ${...}, you can put a variable or an expression such as ${clicks + 1}. Quote marks do not interpolate: "Hi ${name}" contains those characters literally. Backticks also allow strings across multiple lines. Change name and clicks; the message is composed from the new values.
Compare values and types without surprises
=== compares both value and type; == may convert types before comparing. That is why 3 == "3" is true while 3 === "3" is false. For most program comparisons, use === and convert data explicitly when you mean to compare numbers.
const inputValue = "3";
const number = Number(inputValue);
console.log(inputValue === 3); // false
console.log(number === 3); // true
console.log(Number.isNaN(Number("hello"))); // trueNaN marks an invalid numeric calculation; use Number.isNaN to detect it rather than comparing it with ===. Also, typeof null returns "object" because of a historical language quirk: to check whether a value is specifically null, use value === null. Explicit checks avoid invisible conversions and unexpected results.
Truthy and falsy values
if can check a value directly: JavaScript treats it as truthy or falsy. false, 0, "", null, and undefined are falsy; a string containing a space is truthy. That is why checking an input with name.trim() !== "" is safer than only using if (name).
const name = "Ada";
const greeting = name ? `Hi ${name}` : "Enter your name";
console.log(greeting);The conditional operator is condition ? valueIfTrue : valueIfFalse, useful for a short choice. value ?? fallback uses the fallback only for null and undefined; value || fallback uses it for any falsy value, including zero and an empty string. If zero is valid, ?? avoids replacing it by mistake.
A variable remembers the clicks
The first script responds but does not remember how many clicks happened. A variable is a name associated with a value. Write let clicks = 0 before the listener: it starts at zero and can receive a new number. Replace all of script.js with this complete version:
const button = document.querySelector("#button");
const result = document.querySelector("#result");
let clicks = 0;
button.addEventListener("click", () => {
clicks = clicks + 1;
result.textContent = "Clicks: " + clicks;
});Save, reload and click three times: the paragraph shows “Clicks: 1”, “Clicks: 2”, “Clicks: 3”. On each click, the right side of clicks = clicks + 1 calculates the next number; = assigns it to clicks. let allows that new assignment. const fits button and result, because those names keep referring to the same elements in this script.
clicks is outside the listener function: it remains available between presses. Declaring it inside would start it from zero on every click. Reloading the page resets it because, for now, the value lives only in the open page.
A question leads to a choice
We want a special message on the third click. The question “is the click count 3?” produces true or false. === compares two values without automatically turning text into a number. if runs a block when the answer is true; else handles the other cases.
Keep the first three lines of script.js. Replace only the block starting with button.addEventListener with this:
button.addEventListener("click", () => {
clicks = clicks + 1;
if (clicks === 3) {
result.textContent = "You reached three clicks!";
} else {
result.textContent = "Clicks: " + clicks;
}
});Reload: the first two clicks show the number; the third shows the special message; the fourth shows “Clicks: 4”. Change 3 to 2, save and reload: the special message moves to the second click. You changed a rule, not the HTML. clicks === "3" would be false because "3" is text and clicks is a number.
More cases: else if and switch
With else if, JavaScript checks several conditions in order and uses the first true block. The final else covers the remaining cases. This is clear for ranges or combined rules:
if (clicks === 0) {
result.textContent = "Start with one click";
} else if (clicks < 3) {
result.textContent = `Clicks: ${clicks}`;
} else {
result.textContent = "Goal reached";
}switch compares one expression against exact values. Each case names a value; break prevents continuing into the next case. default handles the rest. For numeric ranges, if is clearer; for many outcomes of one exact value, switch can read better.
switch (clicks) {
case 0: result.textContent = "No clicks"; break;
case 3: result.textContent = "Three clicks"; break;
default: result.textContent = `Clicks: ${clicks}`;
}Give a repeatable job a name
The message choice can live in a function: a named group of instructions you can call when needed. Inside the parentheses you write the parameter, the name of the data the function receives. return gives the result back to the place that called the function and ends that call. Here the result is text. Replace script.js with this complete version:
const button = document.querySelector("#button");
const result = document.querySelector("#result");
let clicks = 0;
function messageFor(clickCount) {
if (clickCount === 3) {
return "You reached three clicks!";
}
return "Clicks: " + clickCount;
}
button.addEventListener("click", () => {
clicks = clicks + 1;
result.textContent = messageFor(clicks);
});Reload and click four times: the result matches the previous chapter. When you write messageFor(clicks), you pass the current clicks value into the function. Inside, that value is called clickCount: it is a parameter. return gives text back to the call; the function ends at return.
Try messageFor(2) and messageFor(3) in the Console: you get different text without changing the visible counter. The function prepares text; the listener decides when to use it and writes it into the DOM. This helps you see which code calculates and which code changes the page.
Function forms and default parameters
You have seen function and an arrow function used as a callback. If an arrow function body has one expression, that expression is returned implicitly; multiple statements need braces and return.
function double(number) {
return number * 2;
}
const triple = (number) => number * 3;
const greet = (name, greeting = "Hello") => `${greeting}, ${name}`;
console.log(double(4), triple(4), greet("Ada"));Names in a definition are parameters; values passed to a call are arguments. In greet("Ada"), greeting uses its default. Arrow and declared functions are not always interchangeable: an arrow does not create its own this. Choose the form that makes the function clear. triple is the function; triple(4) runs it.
Where does a variable exist?
A variable declared inside a function’s braces is local: the rest of the script cannot read it directly. clickCount exists inside messageFor; clicks is declared outside, so the listener can read it. Try this small experiment in the Console:
{
const number = 2;
console.log(number); // 2
}
// "number" is no longer available here.Braces create a block. With let and const, a name exists in the block where it was declared. Use const for a name you do not reassign and let when you will assign a new value. This does not mean const makes everything immutable: later you will see that an array’s contents can change.
The function passed to addEventListener is a callback: the browser keeps it and calls it when the click happens. () => { ... } defines a function without naming it. The definition happens when the page loads; its body runs only when you click.
var and declaration order
Today, declare variables with const when the name will not be reassigned, and with let when it will change. var is an older declaration: it is scoped to a function rather than a block and allows the same name to be reused in one scope, making mistakes easier.
if (true) {
let inside = "visible here";
var outside = "visible in the function";
}
console.log(outside);
// console.log(inside); // ReferenceErrorvar and function declarations are processed before their scope runs; this behavior is often called hoisting. That does not make it a good idea to use them before they appear. let and const exist in their block, but cannot be used before the declaration line: that interval is the temporal dead zone, and accessing the name throws an error. Write declarations before their use to keep the flow readable.
A function can remember its context
A closure forms when an inner function keeps accessing variables from the block where it was created, even after that block has finished. It is not special syntax: it is how JavaScript keeps that context available.
function createCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const next = createCounter();
console.log(next()); // 1
console.log(next()); // 2createCounter has finished, but the returned function keeps access to count. Each call updates that private value. The click listener can also read clicks because its callback was created in the same context. Closures help keep state without making it global; they do not automatically make data safe or immutable.
Read a name entered on the page
So far the script knows only about clicks. Add a field to index.html, before the button. The label says what the field is for; for="name" connects it to the input’s id.
<label for="name">Your name</label>
<input id="name" type="text">An input exposes typed text through value. trim() removes spaces at the start and end; !== "" asks whether the remaining text differs from an empty string. Replace script.js with this complete version. Before building the message, it reads the field; if the field is empty, it shows only the count.
const button = document.querySelector("#button");
const result = document.querySelector("#result");
const nameField = document.querySelector("#name");
let clicks = 0;
function messageFor(clickCount) {
if (clickCount === 3) {
return "You reached three clicks!";
}
return "Clicks: " + clickCount;
}
button.addEventListener("click", () => {
clicks = clicks + 1;
const name = nameField.value.trim();
if (name !== "") {
result.textContent = "Hello, " + name + ". " + messageFor(clicks);
} else {
result.textContent = messageFor(clicks);
}
});Reload, type “Ada” and click: you see “Hello, Ada. Clicks: 1”. Clear the name and click again: you see only the count. value reads the field’s current text; trim() removes spaces at both ends; !== "" asks whether nonempty text remains. name is created inside the listener and read again on each click.
textContent displays what you type as text without interpreting it as HTML. Enter <b>Ada</b> in the field: you will see the characters, not a bold name.
Events beyond clicks
addEventListener connects a function to an event; the browser calls it when the event happens. The function is a callback. input fires while a field changes; change signals a committed change; submit is for sending a form.
const field = document.querySelector("#name");
const preview = document.querySelector("#preview");
field.addEventListener("input", () => {
preview.textContent = field.value;
});Here the preview follows what you type. For a form, listen for submit. Wrap the field and submit button in this structure, with a place for the message:
<form id="greeting-form">
<label for="name">Your name</label>
<input id="name" type="text">
<button type="submit">Send</button>
</form>
<p id="form-response"></p>The callback receives an event object; event.preventDefault() stops the browser's normal submission when JavaScript will handle the page:
const form = document.querySelector("#greeting-form");
const nameField = document.querySelector("#name");
const formResponse = document.querySelector("#form-response");
form.addEventListener("submit", (event) => {
event.preventDefault();
formResponse.textContent = `Hello ${nameField.value.trim()}`;
});After stopping submission, show a clear result: do not leave the button without a response. Keyboard input can produce the same events: submitting with Enter should work as well as clicking the button.
One listener for the whole list
An event first travels down the ancestors to its target during capture, then travels back up from the target during bubbling. By default, a listener runs during bubbling; the third argument to addEventListener can request capture. A click on a button can therefore also reach its container. That means one listener on the container can handle clicks from many child elements, including ones added later. This technique is called event delegation.
const list = document.querySelector("#items");
list.addEventListener("click", (event) => {
const button = event.target.closest("button[data-action]");
if (!button || !list.contains(button)) return;
console.log("Action:", button.dataset.action);
});event.target is where the event started; event.currentTarget is the element running this listener. closest searches for the nearest matching button. Delegation avoids adding one listener per item. stopPropagation() can stop an event from travelling further, but use it only when you really want to prevent other containers from reacting.
Forms and data validation
Inputs can be empty or contain invalid values. Read the text, trim surrounding spaces, and check a number before using it. An empty string converted with Number() becomes zero; non-numeric text becomes NaN.
const text = goalField.value.trim();
const goal = Number(text);
if (text === "") {
result.textContent = "Enter a value";
} else if (!Number.isFinite(goal) || goal < 1) {
result.textContent = "Enter a number greater than zero";
} else {
result.textContent = `Goal: ${goal}`;
}Number.isFinite excludes NaN and infinities. Checking the text distinguishes an empty field from a valid zero. HTML also provides required, min, and max, but code still needs to handle the values it receives. Try an empty field, zero, letters, and a valid number; invalid and valid input should produce different messages.
Your turn: add Reset
Before moving on, add a second button below the counter button. The expected result is exact: two clicks on the first button, Reset, then another click should show 1, 2, 0, 1. The name may remain in the field.
<button id="reset" type="button">Reset</button>In script.js, find the new button, listen for its click, assign 0 to clicks and update the text. Try it yourself first: you already know querySelector, addEventListener, = and textContent.
Show one possible solution
Append this block to script.js:
const resetButton = document.querySelector("#reset");
resetButton.addEventListener("click", () => {
clicks = 0;
result.textContent = "Clicks: 0";
});Reset changes both the value kept in clicks and the visible text. Changing only the text would bring back the old count on the next click.
A number typed in a field is still text
An HTML input returns a string even with type="number". That matters when choosing a goal: "3" + 1 produces "31", while Number("3") + 1 produces 4. Try both expressions in the Console before continuing.
In index.html, after the result paragraph, add a field, a check button and a paragraph for the response:
<label for="goal">Click goal</label>
<input id="goal" type="number" min="1" step="1">
<button id="check-goal" type="button">Check goal</button>
<p id="goal-result" aria-live="polite"></p>The new code uses Number() to turn the field’s text into a number. It first checks that the field is not empty and that Number.isInteger() confirms a whole number above zero. || means “or”: one problem is enough to ask for a correction. ! reverses a boolean value. If the input is valid, else if checks whether clicks >= goal, meaning the count is greater than or equal to the goal; else calculates the clicks remaining. At the end of script.js, after Reset, add this block:
const goalField = document.querySelector("#goal");
const checkGoalButton = document.querySelector("#check-goal");
const goalResult = document.querySelector("#goal-result");
checkGoalButton.addEventListener("click", () => {
const text = goalField.value.trim();
const goal = Number(text);
if (text === "" || !Number.isInteger(goal) || goal < 1) {
goalResult.textContent = "Enter a whole number above zero.";
} else if (clicks >= goal) {
goalResult.textContent = "Goal reached!";
} else {
goalResult.textContent = "Clicks remaining: " + (goal - clicks) + ".";
}
});Enter 3, click the counter twice and press “Check goal”: you see “Clicks remaining: 1.”. After one more click, you see “Goal reached!”. An empty field or 0 shows the correction message. Number() converts the text; Number.isInteger() checks for a whole number; || means “or”, so one invalid condition is enough to enter the first block. ! reverses a boolean answer; >= means “greater than or equal to”.
Keep the empty-field check: Number("") is 0. Change the goal to 5 and check that the remaining click count changes. Here you validate a person’s input before using it in a calculation.
A list of values: the array
So far you have worked with one value at a time. To keep several milestones in order, use an array. Square brackets create the list; commas separate its items. Every position has an index starting at 0: milestones[0] reads the first value. length tells you how many items there are. Try this block in the Console: do not copy it into script.js.
{
const milestones = [3, 5, 10];
console.log(milestones[0]); // 3
console.log(milestones[1]); // 5
console.log(milestones.length); // 3
milestones.push(15);
console.log(milestones.length); // 4
console.log(milestones.includes(5)); // true
}The first item has index 0; the second has index 1. length tells you how many items there are. push(15) adds a value at the end, so the second reading of length is 4. includes(5) returns true because 5 is in the list. Change 5 to 8 in the includes call and run the whole block again: you will see false.
const stops you from assigning a new array to the name milestones, but push can change the existing array. If you want a list to stay unchanged, avoid methods that change it. An array is useful when order matters or when you will perform the same action on several items.
Array methods: map, filter, and find
for...of visits items one at a time. Other methods describe a result directly: map transforms each item into a new array; filter keeps items that pass a condition; find returns the first item that passes it.
const milestones = [3, 5, 10];
const labels = milestones.map((n) => `At ${n} clicks`);
const larger = milestones.filter((n) => n >= 5);
const next = milestones.find((n) => n > 3);
console.log(labels, larger, next);The passed function receives each item; the one passed to filter must return a truthy value to keep it. find returns undefined if nothing matches. These methods do not change the starting array; push does. Choose a method based on the result you need and check whether it changes shared data.
Choose the right method for a list
map, filter, and find answer different questions. forEach performs an action for each item and does not create a transformed list. some asks whether at least one item matches a condition; every asks whether they all do.
const clicks = [1, 2, 3, 4];
const doubled = clicks.map((number) => number * 2);
const even = clicks.filter((number) => number % 2 === 0);
const hasLargeValue = clicks.some((number) => number > 3);
const allPositive = clicks.every((number) => number > 0);
const total = clicks.reduce((sum, number) => sum + number, 0);reduce accumulates values into one result; here it starts at 0 and adds each number. Use it when the accumulation makes the code clearer, not just to replace every loop. sort changes the original array and, without a comparator, sorts values as text. For numbers, use numbers.sort((a, b) => a - b); to keep the original array, copy it first or use toSorted in browsers that support it.
Map and Set for other kinds of collections
Arrays and objects cover many cases, but JavaScript has collections with different rules. A Set stores unique values; a Map associates keys and values and can even use an object as a key.
const seen = new Set(["it", "en", "it"]);
seen.add("fr");
console.log(seen.has("en"), seen.size); // true, 3
const counts = new Map();
counts.set("clicks", 3);
console.log(counts.get("clicks")); // 3Use an array when item order and repetition matter. An object suits a group of named properties; a Map is useful for dynamic associations or non-string keys. You do not need to choose a “more advanced” collection: choose the one that makes the data rule clear.
Name the data: the object
A threshold alone does not tell the whole story. An object groups named data, called properties. Here a milestone has a threshold and a label; braces create the object and colons separate names from values. A dot reads a property: milestone.threshold is a number and milestone.label is a string.
{
const milestone = { threshold: 3, label: "First milestone" };
console.log(milestone.threshold); // 3
console.log(milestone.label); // First milestone
console.log(milestone["threshold"]); // 3
milestone.threshold = 5;
console.log(milestone.threshold); // 5
}A dot reads a property: milestone.threshold is a number, milestone.label is a string. You can also write milestone["threshold"], useful when the property name comes from a variable. To change a property, assign milestone.threshold = 5. As with arrays, const protects the name from reassignment; it does not freeze the object’s contents.
Arrays and objects serve different needs: an array holds a sequence; an object names the parts of one piece of data. For several complete milestones, put several objects inside an array. Now you will use them to build a visible list.
Extract values from arrays and objects
Destructuring assigns object properties or array positions to separate names. It reduces repetition when you need data from a structured value in several places.
const person = { name: "Ada", clicks: 3 };
const { name, clicks: clickTotal } = person;
const [first, second] = ["start", "continue"];
console.log(name, clickTotal, first, second);In an object, you can rename a property with clicks: clickTotal. In an array, position matters: first receives the item at index zero. If a property might be missing, provide a default with const { theme = "light" } = preferences;. Destructuring reads values; it does not remove properties from the object.
Properties, methods, and this
An object can contain functions: a function in a property is a method. Properties describe data; methods describe operations on that data.
const counter = {
clicks: 0,
increase() {
this.clicks += 1;
return this.clicks;
}
};
console.log(counter.increase()); // 1In counter.increase(), this refers to the object receiving the call. If you take the method out and call it alone, its context can change. Arrow functions do not have their own this, so this example uses method syntax. One structured value only needs an object; use a class when you need many instances with the same shape.
Classes and instances
A class describes a shared shape for creating objects; each created object is an instance. constructor sets starting data and new creates an instance.
class Counter {
constructor(name) {
this.name = name;
this.clicks = 0;
}
increase() { this.clicks += 1; }
}
const first = new Counter("A");
const second = new Counter("B");
first.increase();
console.log(first.clicks, second.clicks); // 1, 0Each instance shares methods but keeps separate data. Classes are useful when this shape recurs; one object often only needs { name: "A" }. This guide introduces class syntax and its link to prototypes. Inheritance is a later topic; it is not needed for simple classes.
Collect the rest and spread values
The three dots have different roles depending on where they appear. In destructuring they collect remaining items with rest; in an array, object, or function call they expand items with spread.
const [first, ...others] = ["a", "b", "c"];
const base = { theme: "light", language: "en" };
const preferences = { ...base, language: "it" };
function show(first, ...rest) {
console.log(first, rest);
}
show("start", "example", "end");rest collects the arguments after the first; preferences is a new object with the values from base and an updated language. Spread creates only a shallow copy: if a property contains another object or array, that inner value is still shared. Spread alone does not solve every reference problem.
Where do object methods come from?
JavaScript objects can delegate property lookup to a linked object called their prototype. If a property is not found on the object itself, JavaScript looks along this chain. This is how, for example, an array can use shared methods such as map.
const colors = ["blue", "yellow"];
console.log(Object.getPrototypeOf(colors) === Array.prototype); // true
console.log(typeof colors.map); // "function"
class Reminder {
constructor(text) { this.text = text; }
describe() { return `Reminder: ${this.text}`; }
}The describe method is shared through the class prototype, while text belongs to each instance. Classes provide a more familiar syntax for creating objects linked through this chain. To start, use class when multiple instances share behavior; you usually do not need to edit prototype directly.
When a property might be missing
If data may be missing, reading one of its properties directly can throw an error. Optional chaining (?.) stops the lookup and returns undefined when the value on the left is null or undefined.
const profile = { name: "Ada" };
const city = profile.address?.city;
const displayName = profile.name ?? "Guest";
console.log(city, displayName); // undefined, "Ada"?? uses the value on the right only when the left side is null or undefined. Unlike ||, it keeps valid values such as 0, false, and "". These operators make optional data easier to handle, but they do not replace checking data that comes from elsewhere.
Copying arrays and objects: values and references
When you assign a number to a new name, that name receives the value. With arrays and objects, a simple assignment creates another name for the same object: changing it through either name is visible through both.
const first = [3, 5];
const alias = first;
alias.push(10);
console.log(first); // [3, 5, 10]
const copy = [...first];
copy.push(12);
console.log(first); // [3, 5, 10]
console.log(copy); // [3, 5, 10, 12]The [...first] syntax creates a shallow new array. For objects you can also write { ...settings }. “Shallow” means nested values are still shared: if an object contains another object, this copy does not duplicate it deeply. Knowing whether data is shared helps explain changes that seem to appear in several places.
Repeat without copying the same code
With three milestones, you could write three separate conditions. A loop does the same work for each item of an array. for...of takes one item at a time. In index.html, after the goal elements, add:
<button id="show-milestones" type="button">Show milestones</button>
<ul id="milestone-list" aria-label="Milestones reached"></ul>When you press the new button, replaceChildren() empties the list, then the loop rebuilds it. For each reached threshold, createElement("li") makes an item, textContent gives it text and append adds it to the list. With five clicks you will see two items. At the end of script.js, after the goal check, add:
const milestones = [
{ threshold: 3, label: "First milestone" },
{ threshold: 5, label: "Second milestone" },
{ threshold: 10, label: "Third milestone" }
];
const showMilestonesButton = document.querySelector("#show-milestones");
const milestoneList = document.querySelector("#milestone-list");
showMilestonesButton.addEventListener("click", () => {
milestoneList.replaceChildren();
for (const milestone of milestones) {
if (clicks >= milestone.threshold) {
const item = document.createElement("li");
item.textContent = milestone.label;
milestoneList.append(item);
}
}
});Reload, click the counter five times and press “Show milestones”: two items appear. Press Reset and then “Show milestones” again: the list is empty. for...of visits each object; if checks whether its threshold is reached. createElement("li") creates an item; append adds it to the list. replaceChildren() removes previous items before rebuilding, so the earlier Reset code still works.
Try adding a fourth object with threshold 12. You do not need a fourth if: the loop will include it automatically. That is the practical difference between a list of data and copied instructions.
for and while loops
Use for...of to visit array items. The classic for is useful when you need an index: it contains a starting value, condition, and update. while repeats while its condition is true.
const milestones = [3, 5, 10];
for (let index = 0; index < milestones.length; index += 1) {
console.log(index, milestones[index]);
}
let wait = 3;
while (wait > 0) {
wait -= 1;
}Indexes start at zero, and the last one is length - 1. In a while loop, update the checked value: otherwise the condition may remain true forever. break ends a loop and continue skips to the next turn; use them when they make the rule clearer.
Persistence: localStorage and JSON
Variables reset when you close the page. localStorage keeps strings between visits. Convert numbers and structures: JSON.stringify creates JSON text and JSON.parse rebuilds the value.
const settings = { clicks: 3, theme: "light" };
localStorage.setItem("settings", JSON.stringify(settings));
const text = localStorage.getItem("settings");
const loaded = text === null ? null : JSON.parse(text);
console.log(loaded?.clicks); // 3A missing key returns null; ?. reads a property only when the value is not null or undefined. A real project should also handle malformed saved data, which can make JSON.parse fail. Do not store passwords or private data here: anyone using the browser can read it. Persistence is a project choice, not a requirement for the counter.
JSON is not yet a JavaScript object
JSON.stringify converts JavaScript data to JSON text; JSON.parse converts it back and can throw an error if the text is not valid JSON. localStorage stores strings, so conversion is needed when saving objects.
const text = '{"clicks":3}';
try {
const data = JSON.parse(text);
if (typeof data.clicks === "number") {
console.log(data.clicks);
}
} catch (error) {
console.error("The saved text is not valid JSON", error);
}Valid JSON can still contain missing fields or unexpected types. After parsing, check the shape of the data before using it: valid syntax does not guarantee the contents suit your program. JSON does not preserve functions, methods, undefined, or every detail of JavaScript objects.
Read errors before changing code
If a click does not produce the expected result, open the Console. Check that script.js is in the same folder as the HTML, that you saved and reloaded, and that IDs match across the two files. A red error often shows the file and line to start from. You can temporarily put console.log(clicks) inside the listener to see whether the count changes.
A missing element is predictable. querySelector returns null; check it before using the element:
{
const element = document.querySelector("#missing");
if (element === null) {
console.log("Element not found");
}
}Other operations can fail even if your code is written correctly, such as a network request. try/catch lets you respond: the instructions in try are attempted; if an error is raised, catch receives it. Here throw new Error(...) creates and raises an error deliberately. Paste the block into the Console and read the message.
try {
throw new Error("Example error");
} catch (error) {
console.log(error.message); // Example error
}Do not use try/catch to hide a mistyped ID: fix the ID. Keep the Console open during the exercises; it helps you distinguish “the code did not run” from “the code ran with the wrong value”.
Handle an error when you can recover
try...catch catches an error thrown in the try block and lets you show a message or choose a recovery in catch. Do not wrap the whole program: catch close to the operation that can fail, and when you have a useful response to give.
function readSettings() {
try {
const text = localStorage.getItem("settings");
return text ? JSON.parse(text) : {};
} catch (error) {
console.error("Could not read settings", error);
return {};
}
}Syntax errors prevent a file from being parsed; reference errors often point to a missing name; type errors report an operation that is invalid for a value; a logic error can produce the wrong result without a warning. In the Console, first read the error type and line, then inspect values with console.log or a breakpoint in the Sources panel. Fix one cause at a time.
When a result arrives later
The listener responds to a future click. A timer or network request also finishes later. To see waiting without needing a server, add this to index.html:
<button id="wait" type="button">Start waiting</button>
<p id="wait-status" aria-live="polite">Ready.</p>setTimeout schedules an action for later. new Promise(...) creates a value representing a result that has not arrived yet: the timer will call resolve after the specified delay to signal that the wait has ended. async lets a function use await to wait for that result. The wait pauses that function while the page remains usable. At the end of script.js, add:
const waitButton = document.querySelector("#wait");
const waitStatus = document.querySelector("#wait-status");
function wait(milliseconds) {
return new Promise((resolve) => {
setTimeout(resolve, milliseconds);
});
}
waitButton.addEventListener("click", async () => {
waitStatus.textContent = "Waiting...";
await wait(1000);
waitStatus.textContent = "Wait finished.";
});Press “Start waiting”: you immediately see “Waiting...” and about a second later “Wait finished.”. The counter still responds to clicks during the wait. setTimeout schedules an action for later; a Promise represents a result that will arrive. async lets you use await: this function pauses until the Promise finishes while the rest of the page keeps working.
A request with fetch() also returns a Promise, but needs an address that actually responds. You have seen the mechanism in an experiment that works by opening your files. To use server data, you will also need to check the response and handle errors.
Why asynchronous code runs later
JavaScript runs synchronous instructions one at a time. When it encounters a timer or request, the browser handles the wait; meanwhile the script can continue. When the result is ready, the browser schedules the work to run after the current code finishes.
console.log("start");
setTimeout(() => console.log("timer"), 0);
Promise.resolve().then(() => console.log("promise"));
console.log("end");The observed order is start, end, promise, timer. A Promise callback enters the microtask queue, which is processed before timer callbacks. You do not need every queue detail yet: remember that “zero wait” does not mean “run now”. Long synchronous functions, however, block the page until they finish.
Combine multiple waits
await makes waiting for one Promise readable. If you have multiple independent jobs, start them together with Promise.all and wait for the results; if one fails, the combined Promise rejects. If you also need to keep the other results, Promise.allSettled is available.
async function loadPage() {
try {
const [user, preferences] = await Promise.all([
fetch("/api/user").then((response) => response.json()),
fetch("/api/preferences").then((response) => response.json())
]);
console.log(user, preferences);
} catch (error) {
console.error("At least one request failed", error);
}
}Both requests start without waiting for each other. With two consecutive await expressions, the second would start only after the first if its Promise is created there. Choose sequential work when one result is needed to start the next step; choose parallel work when the jobs do not depend on each other. In a real request, also check response.ok: fetch does not automatically reject its Promise for an HTTP response such as 404.
Fetch and asynchronous requests
A timer finishes later; a fetch request also returns a Promise, a value representing a future result. The HTTP response and its content are separate steps:
async function loadData() {
try {
const response = await fetch("https://example.com/data.json");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Request failed", error);
}
}The URL is a placeholder: replace it with a real address that returns JSON and allows the request. fetch can complete with a 404 status, so check response.ok. await waits for the response and then JSON conversion; the browser keeps responding while it waits. try/catch lets you handle network or reading errors. To try real requests, start a local server: opening a file with file:// is not the same as serving a website.
Modules: import and export
As script.js grows, you can move functions into other files. export makes a function available; import uses it. Each module has its own scope.
// messages.js
export function messageFor(clicks) {
return `Clicks: ${clicks}`;
}
// script.js
import { messageFor } from "./messages.js";
console.log(messageFor(3));In HTML, load the entry file with <script type="module" src="script.js">. Braces indicate a named export, and the names must match. Modules use paths relative to the importing file and the browser loads them over HTTP, so this structure needs a development server. Split a project when separate files make each part's responsibility clearer; you do not need one module per function.
Annotate a choice in the file
A comment is a note for someone reading the code: JavaScript does not run it. // starts a one-line comment; /* ... */ encloses a multi-line one. You have already seen comments in the Console examples, where they marked expected results.
// These IDs must match those in index.html.
const button = document.querySelector("#button");
const result = document.querySelector("#result");Add this note above the first two lines of script.js: after reloading, the page behaves as before. Write a comment when it explains a choice or a dependency between files; you do not need to repeat what every instruction already says.
Read the project without skipping steps
Read the project in order: HTML creates elements; the DOM makes them findable; a listener waits for an event; a variable stores state; operators and conditions choose what to do; a function prepares a result; JavaScript updates the page. Fields provide text: trim it, convert it only when needed, and validate the value.
Arrays and objects organize data; methods and loops transform it; references and copies explain when a change is shared. Classes create instances with a similar structure. Modules separate files. Timers and fetch show asynchronous results: check responses and errors. localStorage keeps strings between visits. These are distinct ideas, each introduced in its own chapter.
Before the quiz, check three results yourself: the special message appears on click three; with a goal of 5 and two clicks, three remain; after five clicks, the list shows two milestones and becomes empty after Reset and refresh. If a result differs, return to the chapter that introduced that rule.
Check what you have understood
Twenty-five questions about the ideas and experiments in this guide. Each answer includes an explanation.
When you want to continue
You have met core language concepts: values, conditions, functions, scope, closures, arrays, objects, collections, prototypes, the DOM, events, JSON, errors, Promises, and modules. The next step is to use them in more realistic projects: organize multiple screens, validate external data, handle loading, and test your code.
The localStorage and fetch examples are introductions: a complete application must handle invalid saved data, unexpected network responses, and permissions. For deeper study, see the MDN JavaScript Guide.