
16 JavaScript Projects for Beginners (With Source Code)
Start with a counter or a tip calculator, then build a quiz, a to-do list and a weather app. 16 plain JavaScript projects with tested code, graded by level.
The best first JavaScript projects are small browser apps you can finish in an hour or two, like a counter, a tip calculator or a number guessing game. Once those feel easy, build a to-do list that saves to localStorage, a quiz, and a weather app that fetches live data. All 16 projects below use plain HTML and JavaScript with no framework. They’re grouped by level, and every code sample was run and tested in a browser.
| # | Project | Level |
|---|---|---|
| 1 | Counter | Starter |
| 2 | Tip calculator | Starter |
| 3 | Unit converter | Starter |
| 4 | Word counter | Starter |
| 5 | Guessing game | Starter |
| 6 | Digital clock | Starter |
| 7 | FAQ accordion | Developing |
| 8 | Form validator | Developing |
| 9 | Search filter | Developing |
| 10 | Quiz | Developing |
| 11 | Pomodoro timer | Developing |
| 12 | To-do list | Stretch |
| 13 | Memory game | Stretch |
| 14 | Expense tracker | Stretch |
| 15 | Shopping cart | Stretch |
| 16 | Weather app | Stretch |
What you need
You need a web browser and a text editor. If you’d rather not set anything up, use the free Mimo JavaScript compiler, which runs HTML, CSS and JavaScript together (you need a free account). Online editors can block localStorage or network requests, so if the to-do list or weather app doesn’t work there, save it as a file and open it in your browser.
To run a project on your computer:
- Save the code in one file, for example
index.html. - Open the file in your browser.
- Change something, save, and reload the page.
Each example is a complete page. The JavaScript sits in a <script> tag at the end, so the elements it uses already exist when it runs. <html lang="en"> tells screen readers which language to read the page in. The <head> and <body> tags are left out because the browser adds them for you. Some lines break earlier than you’d usually write them, so the code fits on a phone screen.
If nothing happens when you click, open the browser console: right-click the page, choose Inspect, then open the Console tab. The error message tells you which line failed. For more, see how to debug JavaScript.
Starter projects
Each starter project does one thing: it reads a click or some input and updates one part of the page.
1. Counter with limits
A counter with plus, minus and reset buttons that stays between 0 and 10.
What you’ll learn: selecting elements with querySelector, click events, the += operator, and if statements.
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Counter</title>
<p id="count"
aria-live="polite">0</p>
<button id="minus"
aria-label="Decrease">
-
</button>
<button id="plus"
aria-label="Increase">
+
</button>
<button id="reset">
Reset
</button>
<script>
const MIN = 0;
const MAX = 10;
let count = 0;
const countText = document
.querySelector('#count');
const minusBtn = document
.querySelector('#minus');
const plusBtn = document
.querySelector('#plus');
const resetBtn = document
.querySelector('#reset');
function render() {
countText.textContent =
count;
}
function increase() {
if (count < MAX) {
count += 1;
}
render();
}
function decrease() {
if (count > MIN) {
count -= 1;
}
render();
}
function reset() {
count = 0;
render();
}
plusBtn.addEventListener(
'click', increase);
minusBtn.addEventListener(
'click', decrease);
resetBtn.addEventListener(
'click', reset);
render();
</script>
The number lives in the count variable, and render() is the only function that copies it to the page. Every button changes count first, then calls render(). The if checks in increase() and decrease() keep the number between 0 and 10, so a click at a limit changes nothing. The aria-labels give the - and + buttons names that screen readers can read, and aria-live="polite" makes them read out the new number after each click.
Common mistake: changing count but forgetting to update the page. The variable and the text on screen are separate things.
Make it yours: add a number input that sets the step size, or save the count in localStorage like the to-do list does.
2. Tip calculator and bill splitter
Enter a bill, a tip percentage and the number of people, and see the tip, the total and what each person pays.
What you’ll learn: reading form inputs with FormData, type conversion with Number(), rounding numbers with Math.round() and toFixed(), and the form’s submit event.
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Tips</title>
<form id="tips">
<label>Bill
<input name="bill"
type="number" min="0"
step="0.01" required>
</label>
<label>Tip %
<input name="tip"
type="number" min="0"
step="any" value="15"
required>
</label>
<label>People
<input name="people"
type="number" min="1"
value="1" required>
</label>
<button>Calculate</button>
</form>
<p id="result"
aria-live="polite"></p>
<script>
const form = document
.querySelector('#tips');
const result = document
.querySelector('#result');
const money = (amount) =>
amount.toFixed(2);
function calculate(event) {
event.preventDefault();
const data =
new FormData(form);
const bill = Number(
data.get('bill'));
const tipPercent = Number(
data.get('tip'));
const people = Number(
data.get('people'));
const cents = Math.round(
bill * tipPercent);
const tip = cents / 100;
const total = bill + tip;
const each =
total / people;
result.textContent = [
`Tip ${money(tip)}`,
`total ${money(total)}`,
`each ${money(each)}`,
].join(', ');
}
form.addEventListener(
'submit', calculate);
</script>
event.preventDefault() stops the form from reloading the page, which is what forms do by default. new FormData(form) collects the fields, and data.get('bill') reads one by its name. The required and min attributes make the browser reject empty or negative values before your code runs, so you don’t divide by zero people. step="any" lets the tip be a decimal like 12.5.
The tip is bill * tipPercent / 100, so bill * tipPercent is the same tip in cents. Math.round() rounds it to whole cents, and dividing by 100 turns it back into money, so the total is exactly the bill plus the tip you see. Each share is rounded too, so the shares can add up to a cent more or less than the total. aria-live="polite" on the result makes screen readers read it out whenever it changes.
Common mistake: using form values without Number(). A form value is always a string, so '50' + '7.5' gives '507.5' instead of 57.5.
Make it yours: add buttons for 10%, 15% and 20% that fill in the tip field, or round each person’s share up to the next whole number.
3. Unit converter
Type a number, pick a conversion, and see the result update as you type.
What you’ll learn: writing functions that return a value, switch statements, and the difference between the input and change events.
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Converter</title>
<label>Number
<input id="amount"
type="number">
</label>
<label for="unit">
Conversion
</label>
<select id="unit">
<option value="c-to-f">
Celsius to Fahrenheit
</option>
<option value="f-to-c">
Fahrenheit to Celsius
</option>
<option value="km-to-mi">
Kilometers to miles
</option>
<option value="mi-to-km">
Miles to kilometers
</option>
</select>
<p id="result"
aria-live="polite"></p>
<script>
const amount = document
.querySelector('#amount');
const unit = document
.querySelector('#unit');
const result = document
.querySelector('#result');
function convert(n, type) {
switch (type) {
case 'c-to-f':
return n * 1.8 + 32;
case 'f-to-c':
return (n - 32) / 1.8;
case 'km-to-mi':
return n / 1.609344;
case 'mi-to-km':
return n * 1.609344;
}
}
function update() {
if (amount.value === '') {
result.textContent = '';
return;
}
const answer = convert(
Number(amount.value),
unit.value);
result.textContent =
answer.toFixed(2);
}
amount.addEventListener(
'input', update);
unit.addEventListener(
'change', update);
</script>
The input event fires on every keystroke, and change fires when you pick a new option, so both call the same update() function. convert() doesn’t touch the page at all: it takes a number and returns a number, which makes it easy to check on its own in the console.
Common mistake: leaving out return in a case. The code then falls through and runs the next case too. break would stop that, but a function that gives back a value needs return: with break, convert() returns undefined.
Make it yours: add kilograms and pounds, or show the formula under the result.
4. Live word and character counter
A text box that counts words and shows how many characters you have left, turning red near the limit.
What you’ll learn: the input event, string methods like trim() and split(), template literals, and changing text on the page with textContent.
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Word counter</title>
<label for="text">
Message
</label>
<textarea
id="text"
rows="5"
maxlength="200"
></textarea>
<p id="stats"></p>
<script>
const LIMIT = 200;
const field = document
.querySelector('#text');
const stats = document
.querySelector('#stats');
function countWords(text) {
const clean = text.trim();
if (clean === '') {
return 0;
}
return clean
.split(/\s+/).length;
}
function update() {
const text = field.value;
const words =
countWords(text);
const left =
LIMIT - text.length;
stats.textContent =
`${words} words, ` +
`${left} chars left`;
const warn = left < 20;
stats.style.color =
warn ? 'crimson' : '';
}
field.addEventListener(
'input', update);
update();
</script>
trim() removes spaces at the start and end, and split(/\s+/) splits on any run of spaces, tabs or line breaks, so two spaces between words still count as one gap. The maxlength attribute stops typing at 200 characters, and the script only reports what’s left.
Common mistake: counting words with text.split(' '). An empty box then counts as one word, and double spaces add extra words.
Make it yours: show an estimated reading time, or count sentences by splitting on ., ! and ?.
5. Number guessing game
The page picks a secret number from 1 to 100 and tells you whether each guess is too high, too low or close.
What you’ll learn: random numbers with Math.random(), if, else if and else, and measuring distance with Math.abs().
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Guessing game</title>
<form id="game">
<label>
Guess a number
from 1 to 100
<input id="guess"
type="number" min="1"
max="100" required>
</label>
<button>Guess</button>
</form>
<p id="result"
aria-live="polite"></p>
<button id="again" hidden>
Play again
</button>
<script>
const form = document
.querySelector('#game');
const guessInput = document
.querySelector('#guess');
const result = document
.querySelector('#result');
const againBtn = document
.querySelector('#again');
let secret;
let tries;
function startGame() {
secret = 1 + Math.floor(
Math.random() * 100);
tries = 0;
result.textContent = '';
form.hidden = false;
againBtn.hidden = true;
guessInput.focus();
}
function hintFor(guess) {
const gap = Math.abs(
guess - secret);
const low =
guess < secret;
if (gap === 0) {
return 'Correct!';
} else if (gap <= 5) {
return low
? 'Close! Go higher.'
: 'Close! Go lower.';
} else if (low) {
return 'Too low.';
} else {
return 'Too high.';
}
}
function checkGuess(event) {
event.preventDefault();
const guess = Number(
guessInput.value);
tries += 1;
result.textContent =
`${hintFor(guess)} ` +
`Tries: ${tries}`;
guessInput.value = '';
if (guess === secret) {
form.hidden = true;
againBtn.hidden = false;
againBtn.focus();
}
}
form.addEventListener(
'submit', checkGuess);
againBtn.addEventListener(
'click', startGame);
startGame();
</script>
Math.random() returns a decimal from 0 up to (not including) 1. Multiplying by 100, rounding down and adding 1 gives a whole number from 1 to 100. Math.abs() turns the difference into a positive distance, gap, so one check covers guesses on either side. After a win, focus moves to Play again, so keyboard users can start the next round right away.
Common mistake: calling Math.random() inside checkGuess(). The secret then changes on every guess and the game can’t be won on purpose.
Make it yours: limit the player to 7 tries, or keep the best score across rounds.
6. Digital clock
A clock that shows the current time and updates every second.
What you’ll learn: the Date object, running code on a timer with setInterval(), padding numbers with padStart(), and map().
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Clock</title>
<p id="clock"></p>
<script>
const clock = document
.querySelector('#clock');
const pad = (n) => String(n)
.padStart(2, '0');
function tick() {
const now = new Date();
clock.textContent = [
now.getHours(),
now.getMinutes(),
now.getSeconds(),
].map(pad).join(':');
}
tick();
setInterval(tick, 1000);
</script>
new Date() reads the time on your computer. map(pad) turns each number into a two-digit string, so 9:05:03 shows as 09:05:03, and join(':') glues them together. Calling tick() once before setInterval() fills in the time right away instead of after the first second.
Common mistake: writing setInterval(tick(), 1000). The parentheses call tick once and pass its result, undefined, to setInterval, so the clock never updates.
Make it yours: switch to a 12-hour clock with AM and PM, or show today’s date with toLocaleDateString().
Developing projects
These projects keep track of a few things at once, like the current question and the score, or whether a timer is running.
7. FAQ accordion
A list of questions where clicking one shows or hides its answer, and screen readers hear whether it’s open.
What you’ll learn: working with the DOM and moving to the next element, the hidden attribute, and the aria-expanded attribute.
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>FAQ</title>
<button class="faq"
aria-expanded="false">
What is JavaScript?
</button>
<p hidden>
The language that makes
web pages interactive.
</p>
<button class="faq"
aria-expanded="false">
Do I need a framework?
</button>
<p hidden>
No. Plain JavaScript runs
in every browser.
</p>
<script>
const buttons = document
.querySelectorAll('.faq');
function toggle(btn) {
const answer =
btn.nextElementSibling;
const opening =
answer.hidden;
answer.hidden = !opening;
btn.setAttribute(
'aria-expanded',
opening);
}
buttons.forEach((btn) => {
btn.addEventListener(
'click',
() => toggle(btn),
);
});
</script>
Each answer comes right after its button, so nextElementSibling finds it without extra ids. The hidden property tells you whether the answer is closed, and aria-expanded repeats that for assistive technology, so the two always change together.
Common mistake: making the question a <div> with a click listener. A <button> works with the keyboard and screen readers for free; a <div> doesn’t.
Make it yours: close the other answers when one opens, or add a small arrow that turns when the answer is open.
8. Form validator
A sign-up form that checks each field when you submit, shows a message next to each problem, and clears the message once you fix it. Browser checks are for convenience: a real sign-up form also checks the data on the server.
What you’ll learn: form validation with your own messages, adding and removing classes with classList, and else-if chains.
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Sign up</title>
<style>
.error { color: crimson; }
.invalid {
outline: 2px solid;
outline-color: crimson;
}
</style>
<form novalidate>
<label for="name">
Name
</label>
<input id="name"
aria-describedby="e1">
<p class="error"
id="e1"></p>
<label for="email">
Email
</label>
<input id="email"
type="email"
aria-describedby="e2">
<p class="error"
id="e2"></p>
<label for="password">
Password (8+ characters)
</label>
<input id="password"
type="password"
aria-describedby="e3">
<p class="error"
id="e3"></p>
<button>Sign up</button>
</form>
<p id="result"
aria-live="polite"></p>
<script>
const form = document
.querySelector('form');
const inputs = form
.querySelectorAll(
'input');
const result = document
.querySelector('#result');
function validate(input) {
const value = input.value;
let error = '';
if (value.trim() === '') {
error = 'Required.';
} else if (
!input.checkValidity()
) {
error = 'Not an email.';
} else if (
input.id === 'password'
&& value.length < 8
) {
error = 'Too short.';
}
const ok = error === '';
input.nextElementSibling
.textContent = error;
input.classList.toggle(
'invalid', !ok);
input.ariaInvalid = !ok;
return ok;
}
function onSubmit(event) {
event.preventDefault();
result.textContent = '';
let allValid = true;
inputs.forEach((el) => {
if (!validate(el)) {
allValid = false;
}
});
if (allValid) {
result.textContent =
'Thanks for joining!';
form.reset();
} else {
form.querySelector(
'.invalid').focus();
}
}
function onInput(event) {
const el = event.target;
if (el.classList
.contains('invalid')) {
validate(el);
}
}
form.addEventListener(
'submit', onSubmit);
form.addEventListener(
'input', onInput);
</script>
novalidate turns off the browser’s own pop-ups so your messages show instead, but the browser still checks each field’s type. checkValidity() asks for that result. Only the email field has a rule here (type="email"), so it returns false just for an address the browser rejects, such as a@@b.c. It’s the browser’s built-in check for email format, so you don’t write your own pattern. It still accepts some addresses like a@b, which is why real sign-ups confirm the address by email.
validate() checks every field on submit (not just the first bad one), so the user sees all the problems at once, and focus then moves to the first field with a problem. aria-describedby links each field to its message and aria-invalid marks it as wrong, so screen readers read the error when the field gets focus. Each submit first clears the old success message, so it can’t sit next to new errors. The input listener re-checks only fields already marked invalid, which clears a message as soon as it’s fixed without nagging while someone types for the first time.
Common mistake: checking only on submit and never clearing the message, so the error stays after the field is fixed.
Make it yours: add a "confirm password" field that must match, or disable the button until every field is valid.
9. Search and filter list
A list of programming languages that narrows down as you type in a search box.
What you’ll learn: filtering an array, building elements from data with map(), callback functions, and case-insensitive matching.
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Search</title>
<label>Search
<input id="search"
type="search">
</label>
<p id="count"
aria-live="polite"></p>
<ul id="list"></ul>
<script>
const languages = [
'JavaScript', 'Python',
'Java', 'C#', 'Go',
'Rust', 'Swift', 'Kotlin',
'Ruby', 'PHP',
'TypeScript', 'SQL',
];
const search = document
.querySelector('#search');
const count = document
.querySelector('#count');
const list = document
.querySelector('#list');
function makeItem(text) {
const item = document
.createElement('li');
item.textContent = text;
return item;
}
function render() {
const query = search.value
.trim().toLowerCase();
const found = languages
.filter((name) =>
name.toLowerCase()
.includes(query));
list.replaceChildren(
...found.map(makeItem));
const n = found.length;
count.textContent =
n === 0
? 'No matches.'
: `${n} found`;
}
search.addEventListener(
'input', render);
render();
</script>
filter() keeps only the names that contain the search text, and map() turns each one into an <li>. replaceChildren() swaps the old items for the new ones in one step. Lowercasing both sides means "java" also finds "JavaScript".
Common mistake: overwriting languages with the filtered result. Once a search removes items, clearing the box can’t bring them back. Always filter from the full list.
Make it yours: sort the results alphabetically, or add buttons that filter by type, like front end and back end.
10. Quiz with score and restart
A short multiple-choice quiz that shows one question at a time, tells you if you were right, and shows your score at the end.
What you’ll learn: storing questions as an array of objects, tracking state with an index, and resetting state for a new round.
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Quiz</title>
<p id="prompt"></p>
<fieldset id="picks"
aria-labelledby="prompt">
<button></button>
<button></button>
<button></button>
</fieldset>
<p id="result"
aria-live="polite"></p>
<button id="next" hidden>
Next
</button>
<button id="again" hidden>
Restart
</button>
<script>
const questions = [
{
text: '2 + 3 * 2 = ?',
choices:
['10', '8', '7'],
answer: 1,
},
{
text: '"5" + 1 = ?',
choices:
['6', '51', 'NaN'],
answer: 1,
},
{
text: '7 % 3 = ?',
choices:
['1', '2', '0'],
answer: 0,
},
];
const promptText = document
.querySelector('#prompt');
const picks = document
.querySelector('#picks');
const choiceBtns = Array
.from(picks.children);
const result = document
.querySelector('#result');
const nextBtn = document
.querySelector('#next');
const againBtn = document
.querySelector('#again');
let index = 0;
let score = 0;
function showQuestion() {
const q =
questions[index];
promptText.textContent =
q.text;
choiceBtns.forEach(
(btn, i) => {
btn.textContent =
q.choices[i];
});
result.textContent = '';
nextBtn.hidden = true;
picks.disabled = false;
choiceBtns[0].focus();
}
function choose(choice) {
const q =
questions[index];
const isRight =
choice === q.answer;
if (isRight) {
score += 1;
}
const right =
q.choices[q.answer];
result.textContent =
isRight
? 'Correct!'
: `Answer: ${right}`;
picks.disabled = true;
nextBtn.hidden = false;
nextBtn.focus();
}
function next() {
index += 1;
const done = index ===
questions.length;
if (done) {
showResult();
} else {
showQuestion();
}
}
function showResult() {
const total =
questions.length;
promptText.textContent =
'Quiz complete!';
result.textContent =
`You scored ${score} ` +
`of ${total}.`;
picks.hidden = true;
nextBtn.hidden = true;
againBtn.hidden = false;
againBtn.focus();
}
function restart() {
index = 0;
score = 0;
picks.hidden = false;
againBtn.hidden = true;
showQuestion();
}
choiceBtns.forEach(
(btn, i) => {
btn.addEventListener(
'click',
() => choose(i));
});
nextBtn.addEventListener(
'click', next);
againBtn.addEventListener(
'click', restart);
restart();
</script>
The questions are data, so adding one means adding an object, not writing new HTML. index says which question is showing, and answer stores the position of the right choice, so choice === q.answer checks the click. Array.from() turns the three buttons inside the <fieldset> into an array you can loop over. aria-labelledby="prompt" names the group after the question, so screen readers read it with the answers.
After an answer, the question stays on screen with its feedback until you press Next. Setting picks.disabled = true disables every button inside the <fieldset> at once, so a second click can’t answer twice. Focus moves to Next, then back to the first choice, so the quiz also works with the keyboard. At the end, the score goes into the aria-live result line, so screen readers read it out as focus moves to Restart. restart() puts every piece of state back to its starting value.
Common mistake: resetting index but not score in restart(), so the second round starts with the old points.
Make it yours: shuffle the questions each round, or add a 10-second limit per question.
11. Pomodoro timer
A 25-minute countdown with start, pause and reset buttons, and a message when time is up.
What you’ll learn: setInterval() and clearInterval(), timers in JavaScript, measuring time with Date.now(), using null to mean "no timer running", and the % remainder operator.
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Pomodoro</title>
<p id="time">25:00</p>
<button id="start">
Start
</button>
<button id="pause">
Pause
</button>
<button id="reset">
Reset
</button>
<p id="note"
aria-live="polite"></p>
<script>
const WORK_MS =
25 * 60 * 1000;
let msLeft = WORK_MS;
let endTime = 0;
let timerId = null;
const timeText = document
.querySelector('#time');
const note = document
.querySelector('#note');
const startBtn = document
.querySelector('#start');
const pauseBtn = document
.querySelector('#pause');
const resetBtn = document
.querySelector('#reset');
const pad = (n) => String(n)
.padStart(2, '0');
function render() {
const total = Math.ceil(
msLeft / 1000);
const mins = Math.floor(
total / 60);
const secs = total % 60;
timeText.textContent = [
mins, secs,
].map(pad).join(':');
}
function stop() {
clearInterval(timerId);
timerId = null;
}
function tick() {
msLeft =
endTime - Date.now();
if (msLeft <= 0) {
msLeft = 0;
stop();
note.textContent =
'Time for a break!';
}
render();
}
function start() {
if (timerId !== null) {
return;
}
if (msLeft === 0) {
reset();
}
endTime =
Date.now() + msLeft;
timerId =
setInterval(tick, 1000);
}
function pause() {
if (timerId !== null) {
tick();
stop();
}
}
function reset() {
stop();
msLeft = WORK_MS;
note.textContent = '';
render();
}
startBtn.addEventListener(
'click', start);
pauseBtn.addEventListener(
'click', pause);
resetBtn.addEventListener(
'click', reset);
</script>
Date.now() gives the current time in milliseconds. start() saves the moment the session should end in endTime, and every tick works out the time left, msLeft, from endTime - Date.now(), so the display always matches the real clock. Pause runs one last tick() to save the exact time left, then stops, and the next Start sets a new endTime from it. Math.ceil() rounds up to whole seconds, so 00:00 shows only when time is really up. aria-live="polite" makes screen readers read out the break message.
setInterval() returns an id, and clearInterval() needs that id to stop the timer. Setting timerId back to null in stop() lets start() tell whether a timer is already running, so a second click on Start doesn’t create a second interval. total % 60 is what’s left after taking out whole minutes, which gives the seconds part.
Common mistake: subtracting 1 second on every tick. Browsers slow down timers in background tabs, so ticks arrive late or get skipped, and a 25-minute session ends up taking much longer. Work out the time left from the clock instead.
Make it yours: add a 5-minute break mode, or show the time left in the browser tab title with document.title.
Stretch projects
These projects keep data after a reload, coordinate timing in a game, or load data from the internet.
12. To-do list saved in localStorage
A to-do list where you can add, check off and delete tasks, and the list is still there after you reload the page.
What you’ll learn: localStorage with JSON.stringify() and JSON.parse(), why getItem() returns null for missing data, filtering an array to delete items, and clearing an input field.
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>To-do list</title>
<style>
input:checked + span {
text-decoration:
line-through;
}
</style>
<form>
<label>
New task
<input id="task"
required>
</label>
<button>Add</button>
</form>
<ul id="list"></ul>
<script>
const KEY = 'todo-list';
const form = document
.querySelector('form');
const input = document
.querySelector('#task');
const list = document
.querySelector('#list');
function loadTodos() {
let data;
try {
data = JSON.parse(
localStorage
.getItem(KEY));
} catch {
data = [];
}
const isList =
Array.isArray(data);
if (!isList) {
return [];
}
return data.filter(
(todo) =>
typeof todo?.text ===
'string');
}
let todos = loadTodos();
function save() {
localStorage.setItem(KEY,
JSON.stringify(todos));
}
function makeItem(todo) {
const item = document
.createElement('li');
const label = document
.createElement('label');
const box = document
.createElement('input');
const text = document
.createElement('span');
const del =
document.createElement(
'button');
box.type = 'checkbox';
box.checked = todo.done;
text.textContent =
todo.text;
del.textContent =
'Delete';
del.ariaLabel =
`Delete ${todo.text}`;
box.addEventListener(
'change',
() => toggleTodo(todo));
del.addEventListener(
'click',
() => deleteTodo(todo));
label.append(box, text);
item.append(label, del);
return item;
}
function render() {
list.replaceChildren(
...todos.map(makeItem));
}
function addTodo(event) {
event.preventDefault();
const text =
input.value.trim();
if (text === '') {
return;
}
todos.push({
text: text,
done: false,
});
input.value = '';
save();
render();
}
function toggleTodo(todo) {
todo.done = !todo.done;
save();
}
function deleteTodo(todo) {
todos = todos.filter(
(other) =>
other !== todo);
save();
render();
input.focus();
}
form.addEventListener(
'submit', addTodo);
render();
</script>
The todos array is the source of truth. Every change updates the array and saves it. Adding and deleting also redraw the list, and a delete moves focus to the New task input, because the focused button is gone. Checking a box only saves, because the checkbox already shows its new state and redrawing would take keyboard focus away from it. Each checkbox sits inside a <label> with its text, so clicking the text checks it too and screen readers read the task name.
localStorage only stores strings, so the array goes in as JSON text and comes back out with JSON.parse(). When nothing is saved yet, getItem() returns null, and JSON.parse(null) gives null. That isn’t an array, so the list starts empty. filter() keeps only items with a text string, so damaged data like [null] can’t break the page. A specific key like 'todo-list' makes accidental clashes with other code on the same site less likely.
Common mistake: saving the array without JSON.stringify(). localStorage then stores text like [object Object]. JSON.parse() can’t read that and throws an error, so the try...catch in loadTodos() falls back to an empty list instead of breaking the page.
Make it yours: add an "All / Active / Done" filter, or let users edit a task by double-clicking its text.
13. Memory matching game
Eight face-down cards hide four pairs. Flip two at a time; matching pairs stay open, and the others flip back.
What you’ll learn: shuffling an array with a for loop, click events on generated elements, data- attributes, and setTimeout().
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Memory game</title>
<style>
#board {
display: grid;
grid-template-columns:
repeat(4, 60px);
gap: 8px;
}
#board button {
height: 60px;
font-size: 24px;
}
</style>
<div id="board"></div>
<p id="status">Moves: 0</p>
<p id="note"
aria-live="polite"></p>
<script>
const EMOJIS = [
'🍎', '🍌',
'🍇', '🍒',
];
const board = document
.querySelector('#board');
const statusText = document
.querySelector('#status');
const note = document
.querySelector('#note');
let first = null;
let second = null;
let locked = false;
let moves = 0;
let pairsLeft =
EMOJIS.length;
function shuffle(items) {
const copy = [...items];
for (
let i = copy.length - 1;
i > 0;
i -= 1
) {
const r = Math.random();
const j = Math.floor(
r * (i + 1));
[copy[i], copy[j]] =
[copy[j], copy[i]];
}
return copy;
}
function newCard(emoji, i) {
const card =
document.createElement(
'button');
card.dataset.emoji =
emoji;
card.dataset.label =
`Card ${i + 1}`;
hide(card);
card.addEventListener(
'click',
() => flip(card));
return card;
}
function flip(card) {
if (
locked ||
card.textContent !== '?'
) {
return;
}
const emoji =
card.dataset.emoji;
card.textContent = emoji;
card.ariaLabel = emoji;
const label =
card.dataset.label;
note.textContent =
`${label}: ${emoji}`;
if (first === null) {
first = card;
return;
}
second = card;
moves += 1;
statusText.textContent =
`Moves: ${moves}`;
checkMatch();
}
function checkMatch() {
const isMatch =
first.dataset.emoji ===
second.dataset.emoji;
if (isMatch) {
pairsLeft -= 1;
note.textContent +=
'. Match!';
endTurn();
return;
}
note.textContent +=
'. No match.';
locked = true;
setTimeout(() => {
hide(first);
hide(second);
endTurn();
}, 800);
}
function hide(card) {
card.textContent = '?';
card.ariaLabel =
card.dataset.label;
}
function endTurn() {
first = null;
second = null;
locked = false;
if (pairsLeft === 0) {
note.textContent =
'You won in ' +
`${moves} moves!`;
}
}
const cards = shuffle([
...EMOJIS, ...EMOJIS,
]).map(newCard);
board.append(...cards);
</script>
The shuffle swaps each card with a random card at or before its position, which gives every order the same chance. Each card stores its emoji in data-emoji and shows ? until it’s flipped. A face-down card’s aria-label gives screen readers its position, like "Card 3", and a face-up card’s label is its emoji. flip() ignores any card that isn’t showing ?, so clicking a face-up card does nothing, and matched pairs simply stay that way. The aria-live message reads out each flip, like "Card 3: 🍎", whether the pair matched, and the win. When two cards don’t match, locked stays true for 800 milliseconds so the player can see them before they turn back.
Common mistake: leaving out the lock. A fast third click then flips another card while the wrong pair is still showing, and first and second end up pointing at the wrong cards.
Make it yours: add a "New game" button and a timer, or use 8 pairs on a bigger board.
14. Expense tracker
Add expenses with a name and an amount and see the running total.
What you’ll learn: summing an array with reduce(), arrow functions, converting input with Number() (more on type conversion), and why decimals need rounding for display.
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Expenses</title>
<form>
<label>Description
<input name="desc"
required>
</label>
<label>Amount
<input name="amount"
type="number"
step="0.01" min="0.01"
required>
</label>
<button>Add</button>
</form>
<ul id="list"></ul>
<p aria-live="polite">
Total:
<span id="total"></span>
</p>
<script>
const form = document
.querySelector('form');
const list = document
.querySelector('#list');
const totalText = document
.querySelector('#total');
const expenses = [];
const money = (amount) =>
amount.toFixed(2);
const addAmount =
(sum, expense) =>
sum + expense.amount;
function toRow(expense) {
const row = document
.createElement('li');
row.textContent =
`${expense.desc}: ` +
money(expense.amount);
return row;
}
function render() {
list.replaceChildren(
...expenses.map(toRow));
const total = expenses
.reduce(addAmount, 0);
totalText.textContent =
money(total);
}
function addExpense(event) {
event.preventDefault();
const data =
new FormData(form);
const desc =
data.get('desc').trim();
if (desc === '') {
return;
}
expenses.push({
desc: desc,
amount: Number(
data.get('amount')),
});
form.reset();
render();
}
form.addEventListener(
'submit', addExpense);
render();
</script>
reduce() walks through the array and calls addAmount() for each expense, carrying a running sum that starts from the 0 you pass as the second argument. The total is calculated from the list every time, so it’s always correct. toFixed(2) hides floating-point noise: 0.1 + 0.2 is 0.30000000000000004 in JavaScript, but it shows as 0.30. A description of only spaces gets past required, so addExpense() trims it and stops if nothing is left.
Common mistake: leaving out the starting value 0 in reduce(). This app then breaks every time. With an empty list, as when the page first loads, reduce() throws a TypeError. With expenses, it starts from the first expense object instead of a number, so the total isn’t a number and money() throws.
Make it yours: add a category dropdown and a total per category, or save the expenses in localStorage like the to-do list.
15. Shopping cart
A small menu with Add buttons and a cart where you change quantities and the total updates.
What you’ll learn: using an object as a lookup and adding and removing object properties, for...in loops, passing callback functions to a helper, and calculating values instead of storing them.
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Cart</title>
<div id="menu"></div>
<ul id="cart"></ul>
<p aria-live="polite">
Total:
<span id="total"></span>
</p>
<script>
const prices = {
Tea: 3.5,
Coffee: 4,
Cake: 5.25,
};
// Item name -> quantity
const cart = {};
const menu = document
.querySelector('#menu');
const cartList = document
.querySelector('#cart');
const totalText = document
.querySelector('#total');
const money = (amount) =>
amount.toFixed(2);
const lineCost = (name) =>
prices[name] * cart[name];
function button(text, run) {
const btn =
document.createElement(
'button');
btn.textContent = text;
btn.addEventListener(
'click', run);
return btn;
}
function change(name, by) {
const qty =
(cart[name] || 0) + by;
if (qty <= 0) {
delete cart[name];
} else {
cart[name] = qty;
}
render();
}
// render() replaced the
// buttons, so focus the
// matching new one, or the
// Add button if the row is
// gone.
function refocus(id, name) {
const again = document
.getElementById(id);
if (again) {
again.focus();
} else {
document.getElementById(
'add' + name).focus();
}
}
function qtyBtn(name, by) {
const word = by > 0
? 'more' : 'less';
const id = word + name;
const btn = button(
by > 0 ? '+' : '-',
() => {
change(name, by);
refocus(id, name);
});
btn.id = id;
btn.ariaLabel =
`One ${word} ${name}`;
return btn;
}
function makeRow(name) {
const row = document
.createElement('li');
const qty = cart[name];
const cost =
money(lineCost(name));
row.append(
qtyBtn(name, -1),
` ${qty} × ${name} `,
qtyBtn(name, 1),
` ${cost}`,
);
return row;
}
function render() {
cartList.replaceChildren(
...Object.keys(cart)
.map(makeRow));
let total = 0;
for (const name in cart) {
total += lineCost(name);
}
totalText.textContent =
money(total);
}
for (const name in prices) {
const price =
money(prices[name]);
const btn = button(
`Add ${name} ` +
`(${price})`,
() => change(name, 1));
btn.id = 'add' + name;
menu.append(btn);
}
render();
</script>
The cart only stores quantities, like { Tea: 2 }. Prices stay in prices, and line totals and the overall total are calculated in render(), so they can’t get out of sync. When a quantity drops to 0, delete removes the item from the cart.
The - and + buttons get an aria-label like "One more Tea", so screen readers know which item they change. render() replaces them on every change, so refocus() puts keyboard focus on the new copy of the button you pressed, or on the item’s Add button once its row is gone.
Common mistake: keeping a separate total variable and adding to it in each click handler. It drifts as soon as an item is removed or a price changes. Calculate it from the cart instead.
Make it yours: add a "Clear cart" button, or apply a discount when the total is over a set amount.
16. Weather app with fetch
Pick a city and see its current temperature, loaded live from the free Open-Meteo API, which needs no API key. The free API is for non-commercial use, which is fine for learning projects.
What you’ll learn: fetching data from an API, async and await, handling errors with try...catch, and showing loading and error states.
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Weather</title>
<label>City
<select id="city">
</select>
</label>
<button id="load">
Get weather
</button>
<p id="output"
aria-live="polite"></p>
<script>
const API = 'https://' +
'api.open-meteo.com' +
'/v1/forecast';
const cities = {
Berlin: [52.52, 13.41],
London: [51.51, -0.13],
'New York':
[40.71, -74.01],
Tokyo: [35.68, 139.69],
};
const city = document
.querySelector('#city');
const button = document
.querySelector('#load');
const output = document
.querySelector('#output');
for (const name in cities) {
city.append(
new Option(name));
}
let loading = false;
async function loadTemp() {
if (loading) {
return;
}
const name = city.value;
const [lat, lon] =
cities[name];
const query =
new URLSearchParams({
latitude: lat,
longitude: lon,
current:
'temperature_2m',
});
const url =
`${API}?${query}`;
output.textContent =
'Loading...';
loading = true;
try {
const response =
await fetch(url);
if (!response.ok) {
throw new Error(
response.status);
}
const data =
await response.json();
const temp = data
.current
.temperature_2m;
output.textContent =
`${name}: ${temp} °C`;
} catch (error) {
output.textContent =
'Loading failed.';
console.error(error);
} finally {
loading = false;
}
}
button.addEventListener(
'click', loadTemp);
</script>
await fetch(url) waits for the response, and await response.json() waits for the body to be read as JSON. The temperature is in data.current.temperature_2m, in °C by default. While a request runs, loading is true and extra clicks return right away, so people can’t fire many requests at once. finally sets it back to false whether the request worked or not. The button itself stays enabled, so keyboard focus stays on it.
Common mistake: expecting fetch() to fail on a 404 or 500. It only rejects when the network fails, so check response.ok and throw your own error.
Make it yours: add wind speed by requesting wind_speed_10m too, or let users type any city using Open-Meteo’s geocoding API.
Tips for finishing your projects
- Pasting is fine to see a project run, but typing the code teaches you more. Reload after every few lines, and you’ll catch typos while they’re easy to find.
- Keep the console open. When nothing happens, there’s often a red error there with a line number.
- Do at least one "Make it yours" idea before moving on. That’s the point where you stop following steps and start building.
- If a project feels too big, cut a feature. A finished small app teaches more than a half-built big one.
Once these feel comfortable, React is a common next step for building bigger interfaces.
Learn JavaScript with Mimo
If you want structured practice between projects, Mimo’s JavaScript course teaches JavaScript step by step with interactive lessons and coding challenges. You learn at your own pace and get a certificate when you finish.
To learn HTML, CSS and JavaScript together, try the Front-End Development career path.
Sign up for free and start with your first lesson.

