JavaScript — Make Pages Come Alive
What you'll learn
- What JavaScript actually does (with zero jargon)
- Variables — boxes that remember things
- Functions — recipes you write once and reuse forever
- Conditionals — how code makes decisions
- Arrays and loops — handling many things at once, not just one
- The DOM — how JavaScript touches the page
- Finish with a real interactive click counter
Everything runs right here. No setup.
The robot in the house 🤖
Remember our house? HTML is the walls, CSS is the paint. JavaScript is a robot living inside that can do things: open doors when someone knocks, count visitors, change the wallpaper at night.
JavaScript is a list of instructions the browser follows, one line at a time, top to bottom.
The first instruction to learn: remember something. We do that with a variable — a labeled box:
let score = 0; // a box called "score" holding 0
const name = "Sara"; // a box that can never be swapped
letmakes a box you can change later (score = score + 1)constmakes a locked box — trying to change it is an error
And to see what's in a box, we use console.log(...) — the robot's mouth. Whatever you put inside, it says out loud in the Console panel.
Run this and watch the Console below. The robot creates two boxes, adds points twice, then announces the result. Change the numbers and run again.
let score = 0;
const player = "Sara";
score = score + 10;
score = score + 5;
console.log(player, "has", score, "points");Create your own boxes:
- A variable
myNameholding your name (text goes in quotes:"...") - A variable
ageholding a number - Print both with
console.log(myName, age)
Functions — recipes 👨🍳
Imagine you make tea 5 times a day. Would you re-explain the whole process every time? No — you'd write the recipe once, name it "make tea", and just say the name.
A function is exactly that: a named recipe.
function greet(person) {
return "Hello, " + person + "!";
}
console.log(greet("Omar")); // Hello, Omar!
console.log(greet("Lina")); // Hello, Lina!
function greet(person)— recipe namedgreetthat needs one ingredient:personreturn— what the recipe hands back when donegreet("Omar")— calling the recipe with a real ingredient
Write once, use a thousand times. This is the single most important idea in programming.
Write a function called add that takes two numbers and returns their sum. Then print add(2, 3) to check it works.
Conditionals — teaching the robot to decide 🤔
Real programs don't just run top to bottom blindly — they make decisions. "If it's raining, take an umbrella. Otherwise, don't." JavaScript writes that exact sentence:
const isRaining = true;
if (isRaining) {
console.log("Take an umbrella");
} else {
console.log("Enjoy the sun");
}
To make decisions you need comparisons, which produce true or false:
5 > 3 // true
5 === 5 // true ("===" means "is exactly equal to")
5 !== 3 // true ("!==" means "is not equal to")
age >= 18 // true if age is 18 or more
⚠️ Common trap: always use === (three equals) to compare values, not = (one equals, which assigns a value and would silently break your logic). This trips up every beginner at least once.
You can chain more conditions with else if:
const score = 75;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 70) {
console.log("Grade: B");
} else {
console.log("Grade: C or below");
}
Write a function checkAge(age) that returns:
"child"if age is less than 13"teen"if age is 13 to 17 (inclusive)"adult"if age is 18 or more
Arrays and loops — many things, one instruction 📋
A variable holds one value. An array holds a whole list — like a shopping list in one box:
const fruits = ["apple", "banana", "mango"];
console.log(fruits[0]); // "apple" — arrays start counting at 0!
console.log(fruits.length); // 3
fruits.push("orange"); // add to the end
Now, what if you want to print every fruit? Writing console.log(fruits[0]), console.log(fruits[1])… by hand doesn't scale. A loop repeats an instruction for you:
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Read it as: "starting at i = 0, while i is less than the list's length, print fruits[i], then add 1 to i, and repeat." This one pattern — loop over an array — is everywhere: rendering a list of products, checking every item in a cart, searching a list of users.
A shorter, modern version that many developers prefer:
for (const fruit of fruits) {
console.log(fruit);
}
This reads even more like English: "for each fruit of fruits, print it."
Write a function sumArray(nums) that adds up every number in the array nums and returns the total, using a loop.
Real-world case study: the search bar on this site 🔍
The roadmap search on this very platform's homepage runs on exactly what you just learned. Conceptually, it does this:
const roadmaps = ["Frontend", "Cyber Security", "AI", "Cloud Computing"];
const query = "cloud";
for (const name of roadmaps) {
if (name.toLowerCase().includes(query)) {
console.log("Match:", name);
}
}
Loop over a list (roadmaps) + a condition (if) that checks each one against what you typed = a working live search. Every "search," "filter," or "sort" feature you've ever used on any website is this same combination, just with more polish around it. You already know the core of it.
The DOM — the robot's hands 🖐️
So far the robot only talks to the console. But it can also touch the page: read it, change it, react to clicks. The page, as JavaScript sees it, is called the DOM (Document Object Model) — think of it as the house's control panel.
Three magic moves:
// 1. GRAB an element (like CSS selectors!)
const btn = document.querySelector("#myBtn");
// 2. LISTEN for something happening
btn.addEventListener("click", function () {
// 3. CHANGE the page
document.querySelector("#msg").textContent = "You clicked!";
});
document.querySelector("#myBtn")— find the element withid="myBtn"addEventListener("click", ...)— "when clicked, run this recipe".textContent = ...— replace the text inside an element
Grab → Listen → Change. That's 90% of everyday frontend JavaScript.
The click counter — the classic first interactive app!
The HTML has a button and a <span id="count">. Write the script so that every click adds 1 to the number shown.
Steps: grab both elements → make a let clicks = 0 box → listen for "click" → increase the box → put it in the span.
Lab exercise 1
JavaScript (Node.js)Graded in Code LabTop three words. Read a block of text from standard input and report its three most frequent words.
Rules: compare words case-insensitively, treat any run of letters, digits and apostrophes as a word (punctuation separates words), and print the three most frequent as word count, one per line, most frequent first. Words with the same count are ordered alphabetically. If the text has fewer than three distinct words, print as many as exist; with no words print no words.
- Counts words case-insensitively
- Ties are broken alphabetically
- Fewer than three distinct words
- No words at all
Example run
- Input
The cat and the hat. THE END, and that's it!
- Expected output
the 3 and 2 cat 1
const fs = require("fs");
const text = fs.readFileSync(0, "utf8");
// TODO 1: lowercase the text and split it into words with a regex such as /[a-z0-9']+/g
const words = [];
// TODO 2: count how often each word appears (a Map or a plain object works)
// TODO 3: sort by count (high first), then alphabetically, keep the first three
// TODO 4: print "word count" per line, or "no words" when there are none
console.log("no words");Hints and instant feedback are in Code Lab. Optional practice: it does not block finishing the lesson.
JavaScript and Python also run in your browser without an account; other languages use the secure server runner and need a free account.
Question 1 of 7
Which keyword makes a box you CAN change later?
Question 2 of 7
What does return do inside a function?
Question 3 of 7
How do you find the element with id="save"?
Question 4 of 7
addEventListener("click", fn) means…
Question 5 of 7
Why should you use === instead of = to compare two values?
Question 6 of 7
What does fruits[0] give you in const fruits = ["apple","banana"]?
Question 7 of 7
What does a for loop let you do?
Level complete 🏆
You now know:
- Variables (
let,const) — remembering things - Functions — reusable recipes with
return - Conditionals (
if/else if/else) — making decisions - Arrays and loops — handling lists, not just single values
- DOM — grab, listen, change
What's next? Practice is everything in JavaScript. Try: a counter that also goes down, a button that changes the page color, a name-greeting input, a search box that filters a list of names as you type. Then continue to Git & GitHub to save your work like a professional — and later React, which builds on everything here.
Practice
Reading is not learning until you run something. Pick one.
Graded lab exercises
- Lab exercise 1JavaScript (Node.js)Not passed yet Try in Code Lab