Dev.to WebDev 🛠 Dev 👁 0 📖 11 min read

5 JavaScript Projects for Practice: Build and Test Real Apps.

The best JavaScript projects for practice are small enough to finish but complex enough to expose real programming problems. An input validator, time calculator, multi-step form, habit tracker and results dashboard cover

5 JavaScript Projects for Practice: Build and Test Real Apps.

The best JavaScript projects for practice are small enough to finish but complex enough to expose real programming problems. An input validator, time calculator, multi-step form, habit tracker and results dashboard cover five skills that appear repeatedly in frontend development: validation, calculations, state, persistence and data transformation.
Each project below is a complete browser application written in HTML, CSS and vanilla JavaScript. There are no frameworks, build tools or dependencies. The aim is not simply to make something that looks right, but to define its behavior, test edge cases and understand why it works.

Comparison of five JavaScript practice projects by difficulty, main skill, and prerequisite

Before you start

You need a modern browser, a text editor and basic familiarity with variables, functions, arrays and event listeners. Download each project ZIP, extract it into a separate folder and open its HTML file in your browser. For the storage example, serve the folder over HTTP using a local development server if possible; storage behavior for file: URLs is not reliably defined.

The examples use inline CSS and JavaScript to keep setup simple. Once a project works, you can move its CSS into style.css and JavaScript into script.js (load the latter with defer). Use the browser console to run the suggested checks. Each project is independent, so you do not need to combine their scripts.

Try to predict the expected output before running a test. That is a useful habit when debugging code: a result is only meaningful when you know what should happen.

Project 1 — Build a form input validator

Level: Beginner. Skills: DOM selection, events, conditionals and accessible error feedback.

Build a form that accepts decimal numbers from 0 to 100. The challenge is not just checking the range. JavaScript converts both an empty string and a string containing only whitespace to zero with Number(). If you convert first, a missing answer can become indistinguishable from a deliberate zero.

The validate() function checks the raw string before conversion. A regular expression defines the accepted decimal format, so hexadecimal and exponent notation are intentionally rejected. Number.isFinite() and the range check enforce the numeric constraint. The function returns either an error object or a value object; the submit handler decides how to display that outcome.

Core JavaScript

function validate(raw) {
  const text = raw.trim();
  if (text === '') return { error: 'Enter a number.' };
  if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(text)) {
    return { error: 'Enter a valid decimal number.' };
  }
  const value = Number(text);
  if (!Number.isFinite(value) || value < 0 || value > 100) {
    return { error: 'Enter a number from 0 to 100.' };
  }
  return { value };
}

Download the complete application

Download Project 1 source code (ZIP)

Extract the ZIP and open project-1-input-validator.html in your browser.

Test it

Project 1 | Validation tests: Input: Empty or whitespace, Expected outcome: Required-field error; Input: 0, Expected outcome: Accepted; Input: 100, Expected outcome: Accepted; Input: 42.5, Expected outcome: Accepted; Input: 101, Expected outcome: Range error; Input: abc or 0x10, Expected outcome: Invalid decimal error

Run these checks in the browser console after opening the application:

console.assert(validate('').error);
console.assert(validate('0').value === 0);
console.assert(validate('100').value === 100);
console.assert(validate('101').error);

Submit an empty field, then correct it to zero. The error should clear when the input becomes valid. The form associates its hint and error with the input, identifies invalid values with aria-invalid and returns focus to the field after an invalid submission. These are accessibility-oriented design choices, not proof of complete accessibility compliance.

Extension challenge: Add minimum and maximum fields and reject a minimum greater than the maximum. This introduces cross-field validation.

Project 2 — Build a JavaScript time calculator

Level: Beginner. Skills: Pure functions, input parsing, arithmetic and formatting.

Calculate elapsed time between two clock times. Subtracting the numbers directly fails for an overnight interval. Instead, convert hours and minutes to minutes since midnight, then use (end - start + 1440) % 1440. For 22:30 to 06:15 the result is 465 minutes, or 7 hours and 45 minutes.

Define the rules before coding: an earlier end time belongs to the next day, equal times mean zero minutes, and intervals must be shorter than 24 hours. This is a clock-time calculation, not a date-aware elapsed-time calculation; daylight-saving transitions and time zones are outside its scope.

Core JavaScript

function toMinutes(value) {
  if (!/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(value)) return null;
  const [hours, minutes] = value.split(':').map(Number);
  return hours * 60 + minutes;
}
function elapsed(start, end) {
  const a = toMinutes(start), b = toMinutes(end);
  if (a === null || b === null) return null;
  return (b - a + 1440) % 1440;
}

Download the complete application

Download Project 2 source code (ZIP)

Extract the ZIP and open project-2-time-calculator.html in your browser.

Test it

Project 2 | Time calculation tests: Start: 09:00, End: 11:30, Expected minutes: 150; Start: 22:30, End: 06:15, Expected minutes: 465; Start: 08:00, End: 08:00, Expected minutes: 0; Start: 23:59, End: 00:00, Expected minutes: 1; Start: 24:00, End: 09:00, Expected minutes: Invalid; Start: Empty, End: 09:00, Expected minutes: Invalid

console.assert(elapsed('09:00', '11:30') === 150);
console.assert(elapsed('22:30', '06:15') === 465);
console.assert(elapsed('08:00', '08:00') === 0);
console.assert(elapsed('24:00', '09:00') === null);

The elapsed() function does not read the DOM. You can test it using ordinary strings, without interacting with the form. Separating calculation from presentation makes the code easier to reuse and debug. The browser's native time controls provide the input strings, while the parser still checks the expected 24-hour format.

Extension challenge: Accept dates as well as times and document whether your calculation represents wall-clock duration or actual elapsed time across time-zone and daylight-saving changes.

Project 3 — Build a multi-step form

Level: Beginner to intermediate. Skills: State, navigation, validation and rendering.

Build a three-step project planner: choose a project name, enter a daily practice duration and review the answers. A form that replaces its inputs at each step can accidentally discard previous answers if the DOM is its only source of state.

The state object holds step, name and minutes. Each input event updates that object. The render function creates the appropriate fields from state; it does not require previous input elements to remain on the page. The advance() function checks the current step and returns a new object containing the next step or an error. The UI uses that result to navigate, while the central state object is updated by the event handlers.

The form moves focus to the step heading after navigation. Invalid submissions instead focus the relevant input. Review values are inserted using textContent, so user-supplied names are displayed as text rather than interpreted as HTML.

Core JavaScript

const state = { step: 0, name: '', minutes: '' };
function validate(step, data) {
  if (step === 0 && !data.name.trim()) return 'Enter a project name.';
  if (step === 1 && (!/^\d+$/.test(data.minutes.trim()) || Number(data.minutes) < 1 || Number(data.minutes) > 120)) return 'Enter a whole number from 1 to 120.';
  return '';
}
function advance(data) {
  const error = validate(data.step, data);
  return error ? { ...data, error } : { ...data, step: Math.min(data.step + 1, 3), error: '' };
}

Download the complete application

Download Project 3 source code (ZIP)

Extract the ZIP and open project-3-multi-step-form.html in your browser.

Test it

Project 3 | Form navigation tests: Action: Click Next with an empty name, Expected outcome: Stay on step 1; Action: Enter a name and click Next, Expected outcome: Move to step 2; Action: Enter 0 or 121 minutes, Expected outcome: Stay on step 2; Action: Enter 30 minutes, then go Back, Expected outcome: Name is retained; Action: Edit an answer from review, Expected outcome: Updated value appears on return; Action: Confirm the review, Expected outcome: Completion screen

console.assert(advance({step:0, name:'', minutes:''}).step === 0);
console.assert(advance({step:0, name:'Calculator', minutes:''}).step === 1);
console.assert(advance({step:1, name:'Calculator', minutes:'0'}).step === 1);
console.assert(advance({step:1, name:'Calculator', minutes:'30'}).step === 2);

The console checks cover progression logic. The navigation and focus checks require interacting with the form in a browser. Notice that state is only held in memory: refreshing the page starts the plan again. Persistence is the next project's subject.

Extension challenge: Add a visual progress indicator that stays synchronized with the step number when the user moves forward or backward.

Project 4 — Build a seven-day habit tracker

Level: Beginner to intermediate. Skills: Arrays, JSON, event handling and localStorage.

Build seven checkboxes representing days of JavaScript practice. Every checked box represents recorded completion; an unchecked box means completion has not been recorded, not necessarily that the user failed.

The application stores seven Boolean values in an array. toggle() returns a new array with one changed value, and count() derives the completion count directly from the current array. Maintaining a separate counter would create another value that could get out of sync.

Browser storage accepts strings, so JSON.stringify() converts the array before saving and JSON.parse() restores it. The decode() function checks that stored data is an array of exactly seven Booleans. Storage access and parsing can fail, so the application falls back to an empty tracker instead of crashing. If writing fails, it displays a warning that progress is temporary.

Core JavaScript

const KEY = 'js-practice-habit-v1';
const empty = () => Array(7).fill(false);
function decode(raw) {
  try {
    const value = JSON.parse(raw);
    return Array.isArray(value) && value.length === 7 &&
      value.every(v => typeof v === 'boolean') ? value : empty();
  } catch { return empty(); }
}
function count(days) { return days.filter(v => v === true).length; }
function toggle(days, index, checked) {
  return days.map((v, i) => i === index ? checked : v);
}
function load(storage) { try { return decode(storage.getItem(KEY)); } catch { return empty(); } }
function save(storage, days) { try { storage.setItem(KEY, JSON.stringify(days)); return true; } catch { return false; } }

Download the complete application

Download Project 4 source code (ZIP)

Extract the ZIP and open project-4-habit-tracker.html in your browser.

Test it

Project 4 | Persistence tests: Action: Check two days, Expected outcome: Count becomes 2; Action: Uncheck one day, Expected outcome: Count becomes 1; Action: Refresh after saving, Expected outcome: Recorded progress is restored, if storage works; Action: Reset all days, Expected outcome: Count becomes 0; Action: Load malformed JSON, Expected outcome: Empty tracker; Action: Block storage writes, Expected outcome: Tracker works in memory and warns

console.assert(count(toggle(empty(), 0, true)) === 1);
console.assert(count(decode('broken JSON')) === 0);
console.assert(count(decode('[true]')) === 0);
console.assert(count(Array(7).fill(true)) === 7);

For a manual persistence test, check a day, reload the page and confirm the checkbox remains selected. Reset it, reload again and verify the reset persisted. localStorage is scoped to the browser's origin, can be cleared and is not a secure place for sensitive information. This example uses numbered days, not calendar dates; it does not roll over automatically each week.

Extension challenge: Replace Booleans with three explicit states: completed, not-completed and not-recorded. That lets the interface distinguish an observed negative outcome from missing information.

Project 5 — Build an interactive results dashboard

Level: Early intermediate. Skills: Data transformation, aggregation, derived state and rendering.

The dashboard accepts up to five JavaScript practice-session durations and displays the total, average, recorded count and a visual comparison. The central rule is that an unrecorded session is not a zero-minute session.

For example, [20, 40, 60, null, null] has a total of 120 and an average of 40 across three recorded sessions. Dividing by five instead produces 24, which answers a different question. If the user explicitly enters zero, that zero is a valid observation and must be included in the denominator.

parseEntry() returns null for blank values, a number for valid entries, or throws an error for invalid input. summarize() expects already validated numbers or null and computes the count, total and average. The dashboard recalculates on input changes instead of storing separate mutable totals. When a field is invalid, it withholds the summary rather than showing a misleading partial result.

Core JavaScript

function parseEntry(raw) {
  const text = raw.trim();
  if (text === '') return null;
  if (!/^\d+$/.test(text)) throw new Error('Use a whole number from 0 to 120.');
  const n = Number(text);
  if (!Number.isSafeInteger(n) || n > 120) throw new Error('Use a whole number from 0 to 120.');
  return n;
}
function summarize(entries) {
  const values = entries.filter(value => value !== null);
  const total = values.reduce((sum, value) => sum + value, 0);
  return { count: values.length, total, average: values.length ? total / values.length : null };
}

Download the complete application

Download Project 5 source code (ZIP)

Extract the ZIP and open project-5-results-dashboard.html in your browser.

Test it

Project 5 | Dashboard tests: Recorded values: None, Count: 0, Total: 0, Average: Unavailable; Recorded values: 20, 40, 60, Count: 3, Total: 120, Average: 40; Recorded values: 0, 40, 60, Count: 3, Total: 100, Average: 33.3 (displayed); Recorded values: 20, 40, 90, Count: 3, Total: 150, Average: 50

console.assert(parseEntry('') === null);
console.assert(parseEntry('0') === 0);
console.assert(summarize([20,40,60,null,null]).average === 40);
console.assert(summarize([0,40,60]).count === 3);
console.assert(summarize([null,null]).average === null);

Enter 121 or a negative number and check that results disappear until the value is corrected. The table displays actual numbers alongside native progress indicators, so the information is not communicated through bar lengths or color alone. This example does not persist values; try integrating the previous project's storage pattern once the calculation and validation behavior are clear.

Extension challenge: Calculate the minimum, maximum and median of recorded values. Decide what each statistic should return for an empty dataset before writing the implementation.

How to turn these practice projects into portfolio projects

A working application is a good start, but a portfolio project should explain the decisions behind its behavior. Add a README describing the problem, setup instructions, input constraints, assumptions and examples. Include a small table of expected results and a screenshot of the actual application. If you deploy a demo, verify the public URL and test it on a narrow screen as well as a desktop browser.

Keep the application small enough to explain in an interview. For example, being able to explain why the dashboard preserves zero while excluding missing values demonstrates more understanding than adding a large chart library without knowing how the average is calculated.

Before calling a project finished, check that:

  • Its main user flow works and invalid inputs are handled.
  • Calculations can be tested independently where practical.
  • Input fields have labels, keyboard focus is visible and error messages are understandable.
  • Empty states, boundary values and unexpected data are covered.
  • The README documents assumptions and known limitations.

Frequently asked questions

What are the best JavaScript projects for beginners?

Start with projects that have a clear input, output and a small number of rules. An input validator and elapsed-time calculator are good first exercises because their core functions can be tested without a complex interface. Move on to forms and trackers as you become comfortable with events and state.

Should I practice vanilla JavaScript before using React?

You do not need to master every browser API before learning a framework, but understanding functions, arrays, objects, events and state makes framework behavior easier to reason about. These projects provide a foundation without adding framework-specific concepts.

How can I practice without following a tutorial line by line?

Read the project requirements and test cases before looking at the implementation. Write your own solution, compare its behavior with the expected results and investigate failures. Then attempt the extension challenge without copying the original solution.

What makes a JavaScript practice project portfolio-ready?

A clear problem, working interface, documented decisions, reproducible tests and understandable code are more useful than feature count alone. A portfolio project should demonstrate that you can explain what happens when inputs are missing, invalid or unexpectedly changed.

Conclusion

These five projects progress from input validation to calculations, state management, persistence and derived results. They share one principle: define the expected behavior before connecting it to the interface. Start with a single project, implement its core function and use the test cases to guide improvements.

AI disclosure: This tutorial and its educational code examples were generated with ChatGPT. The examples are standalone teaching implementations, not production application code. The console checks and manual test scenarios are provided so readers can independently verify the behavior.

Which of these projects would you extend first, and what edge case would you add to its test suite?

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.