HTML
Structure and content.
Make your pages respond. Learn the core of JavaScript, then use it to build something interactive.
Each JavaScript example has a Try it button that loads it into the playground, so you can run it and change it. Your code runs in an isolated sandbox that cannot touch this page.
Part 1
A website has three layers. JavaScript is the one that makes things happen: updating text, responding to clicks, checking a form, or running a game. It runs inside the browser, so no installation is needed. (Despite the name, it is unrelated to Java.)
Structure and content.
Appearance and layout.
Behavior and logic.
Part 2
Put a script element at the end of the body, so the page elements exist before your code looks for them. Use an external file for real projects.
<body>
<h1 id="title">Hello</h1>
<script src="app.js"></script>
</body>console.log("Hello from JavaScript!");Output (in the console)Hello from JavaScript!
You can also write code directly between <script> and </script>, or add defer to a script in the head so it waits for the page.
Common mistake: placing the script above the elements it uses. The code runs before they exist, and you get null.
Part 3
A variable is a named box that stores a value.
const siteName = "CODEX";
let score = 0;
score = score + 10;
console.log(siteName, score);const siteName = "CODEX"; creates a variable that can never be reassigned.let score = 0; creates a variable that can change later.score = score + 10; reads the old value, adds 10, and stores the result.console.log(...) prints the values to the console.OutputCODEX 10
Rule of thumb: use const by default, and let only when the value must change. Name variables in camelCase, like totalScore.
Common mistake: reassigning a const. siteName = "X"; throws "Assignment to constant variable".
Part 4
const name = "Sam"; // string: text
const age = 14; // number
const isStudent = true; // boolean: true or false
const hobbies = ["art", "football"]; // array: an ordered list
const person = { name: "Sam", age: 14 }; // object: named values
console.log(hobbies[0]);
console.log(hobbies.length);
console.log(person.name);
console.log(typeof age);Outputart
2
Sam
number
hobbies[0] reads the first array item. Counting starts at 0.hobbies.length is the number of items.person.name reads a property of an object using a dot.typeof tells you which type a value is.Common mistake: expecting the first item at [1]. Arrays start at index 0, so the last item is at length - 1.
Part 5
console.log(7 + 3); // add
console.log(7 % 3); // remainder
console.log(5 === 5); // equal value and type
console.log(5 === "5"); // different types
console.log(5 !== 3); // not equal
console.log(10 > 3 && 2 > 5); // AND: both must be true
console.log(10 > 3 || 2 > 5); // OR: one is enough
console.log("5" + 3); // string joiningOutput10
1
true
false
true
false
true
53
Use === and !== for comparisons. They check value and type, which avoids surprises. Combine conditions with && (and), || (or), and ! (not).
Common mistake: writing = when you mean ===. A single = assigns a value, it does not compare.
Part 6
Conditions let your code choose. JavaScript checks them from top to bottom and runs the first one that is true.
const score = 72;
if (score >= 90) {
console.log("Excellent");
} else if (score >= 60) {
console.log("Good");
} else {
console.log("Keep practicing");
}OutputGood
The first test fails (72 is not 90 or more), the second passes, so "Good" prints and the else is skipped. Change score to try the other branches.
Common mistake: putting conditions in the wrong order. If you tested score >= 60 first, a score of 95 would print "Good".
Part 7
Loops repeat code. Use for when you know how many times, and while when you repeat until something changes.
for (let i = 1; i <= 3; i++) {
console.log("Round " + i);
}
let countdown = 3;
while (countdown > 0) {
console.log(countdown);
countdown--;
}
console.log("Go!");OutputRound 1
Round 2
Round 3
3
2
1
Go!
let i = 1 sets the start. i <= 3 is the condition that keeps the loop going. i++ adds 1 each time.while loop runs as long as countdown > 0. countdown-- subtracts 1 each round.Common mistake: an infinite loop. If you forget countdown--, the condition never becomes false. Also watch for off-by-one errors, like < versus <=.
Part 8
A function is a reusable block of code. Parameters are its inputs, and return sends back an output.
function add(a, b) {
const total = a + b;
return total;
}
const result = add(2, 3);
console.log(result);
console.log(add(10, 5));Output5
15
function add(a, b) defines a function with two parameters.return total; hands the value back and ends the function.add(2, 3) calls it with the arguments 2 and 3.Scope: a variable created inside a function or block only exists there.
function demo() {
const secret = 42;
console.log(secret);
}
demo();
console.log(secret);Output42
Uncaught ReferenceError: secret is not defined
Common mistake: forgetting return, which makes the function give back undefined, or writing add instead of add(2, 3) so it never runs.
Part 9
The browser turns your HTML into a tree of objects called the DOM. JavaScript can find elements in it and change them.
<h1 id="title">Hello</h1>
<ul id="list"></ul>const title = document.getElementById("title");
title.textContent = "Hello, CODEX!";
title.classList.add("highlight");
const list = document.getElementById("list");
const item = document.createElement("li");
item.textContent = "First item";
list.appendChild(item);getElementById("title") finds the element with that id. querySelector(".card") finds by any CSS selector.textContent changes the text. classList.add, remove, and toggle change CSS classes.createElement makes a new element, and appendChild puts it on the page.Result on the pageThe heading now reads "Hello, CODEX!" and the list shows one item.
Common mistake: using innerHTML with text a visitor typed. It can inject harmful code. Prefer textContent.
Part 10
An event is something that happens: a click, a key press, typing in an input. An event listener runs a function when it does.
<button id="btn">Click me</button>
<p id="out"></p>const btn = document.getElementById("btn");
const out = document.getElementById("out");
let count = 0;
btn.addEventListener("click", function () {
count = count + 1;
out.textContent = "Clicks: " + count;
});Result on the pageEach click updates the text: Clicks: 1, Clicks: 2, and so on.
This exact example is already loaded in the playground below. Run it and click the button in the preview.
Common mistake: writing addEventListener("click", sayHi()). The parentheses call the function immediately. Pass sayHi without them.
Part 11
Errors are normal, and they are useful: the message tells you what went wrong and often where. Use try and catch to handle problems without crashing, and throw to raise your own.
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
console.log(divide(10, 2));
console.log(divide(5, 0));
} catch (err) {
console.log("Error: " + err.message);
}Output5
Error: Cannot divide by zero
console.log(variable) to see what the code is really doing.myVar and myvar are different names.Practice
Edit the HTML and JavaScript, then press Run. Output from console.log and any errors appear in the console below. Your code runs in a sandboxed frame, isolated from this page.
Output preview
Challenges
Each one gets harder. Write the function, then press Check to run it against tests. Passed: 0 of 3.
Final project
Finish the starter below so that your list can add, complete, and remove tasks. Follow the numbered TODO comments, press Run, and test it in the preview. Stuck? Load the finished example and compare it with yours line by line.
Your to-do list
Tick each item when it works in your preview
Stretch goal: show how many tasks are left, or build a click counter instead using the example in Part 10.
Knowledge check
Ran the examples, solved the challenges, and built your list? Mark the lesson complete. Progress is saved in this browser only.
Module 05 complete. Your pages can now think and respond.