JavaScript Project and Interview Prep
Design a typed, tested expense tracker from requirements through deployment, then practice core JavaScript interview questions.
Define Requirements, Architecture, and Data Contracts
Build an expense tracker for a student to record spending, browse entries, and see category totals. Start with correct, testable domain rules; let the UI call those rules rather than duplicate them.
| Requirement | Acceptance check | Out of scope for version one |
|---|---|---|
| Add an expense | Description, category, date, and positive amount are required | Bank account integration |
| List expenses | Newest entries appear first and each has a stable ID | Multi-user sharing |
| Show a total | The total equals the sum of valid saved amounts | Currency conversion |
| Keep data locally | Reloading the page preserves this browser profile data | Cloud synchronization and backups |
| Handle bad input | Invalid entries are rejected with an actionable message | Advanced recurring budgets |
Architecture: Separate Domain, Storage, and UI
Separate the domain model and validation, storage adapter, and UI. Test domain rules without a browser, and replace local storage later without rewriting calculations.
| Module | Responsibility | Depends on |
|---|---|---|
| expense.ts | Types, validation, total and sorting rules | Nothing external |
| expense-storage.ts | Serialize, parse, and persist records | Browser storage interface |
| app.ts | Connect form events, storage, and rendering | Domain and storage modules |
| *.test.ts | Verify rules and boundary behaviours | Vitest and the module under test |
Domain rules should not import the DOM or storage. Inject dependencies at testable boundaries, and avoid libraries that the requirements do not justify.
Domain model: Make the Data Contract Visible
Types document the data shape but do not validate JSON or form values at runtime. Validate untrusted input before using it as an Expense.
export type Category = 'food' | 'travel' | 'study' | 'other'
export type Expense = {
id: string
description: string
amount: number
category: Category
date: string
}
export type ExpenseInput = {
description: string
amount: string
category: string
date: string
}
export function createExpense(input: ExpenseInput, id: string): Expense {
const description = input.description.trim()
const amount = Number(input.amount)
const categories: Category[] = ['food', 'travel', 'study', 'other']
if (description.length === 0) throw new Error('Description is required')
if (!Number.isFinite(amount) || amount <= 0) throw new Error('Amount must be positive')
if (!categories.includes(input.category as Category)) throw new Error('Choose a valid category')
if (Number.isNaN(Date.parse(input.date))) throw new Error('Choose a valid date')
return {
id,
description,
amount,
category: input.category as Category,
date: input.date,
}
}The caller supplies the ID to keep this function deterministic. Choose a stable ID strategy and one documented date format.
Core behaviour: Keep Totals and Ordering Pure
Pure functions are easy to test and reuse. Sort a copy so this module does not mutate another layer’s list.
export function totalExpenses(expenses: Expense[]): number {
return expenses.reduce((total, expense) => total + expense.amount, 0)
}
export function newestFirst(expenses: Expense[]): Expense[] {
return [...expenses].sort((left, right) => {
return right.date.localeCompare(left.date)
})
}For strict financial precision, use integer minor units or an appropriate decimal strategy: binary floating point approximates some decimals. State the demo’s assumptions.
Handle Stored JSON as Untrusted Input
Stored strings may be missing, malformed, or outdated. Parse and validate them at the storage boundary so the UI stays independent of serialization.
import type { Expense } from './expense'
export interface StorageLike {
getItem(key: string): string | null
setItem(key: string, value: string): void
}
const STORAGE_KEY = 'chaduvuko-expenses'
export function loadExpenses(storage: StorageLike): Expense[] {
const raw = storage.getItem(STORAGE_KEY)
if (!raw) return []
try {
const value: unknown = JSON.parse(raw)
if (!Array.isArray(value)) return []
return value.filter((item): item is Expense => {
return item !== null
&& typeof item === 'object'
&& typeof item.id === 'string'
&& typeof item.description === 'string'
&& typeof item.amount === 'number'
&& Number.isFinite(item.amount)
&& typeof item.date === 'string'
})
} catch {
return []
}
}
export function saveExpenses(storage: StorageLike, expenses: Expense[]): void {
storage.setItem(STORAGE_KEY, JSON.stringify(expenses))
}Decide whether corrupt data is reported or recoverable. Extend validation to category, amount, and date; render descriptions as text, never executable HTML.
Verify Rules Before You Polish the Interface
Test validation, totals, sorting, and malformed storage. Build a semantic, labeled form with accessible feedback, then document setup and limitations.
import { describe, expect, it } from 'vitest'
import { createExpense, totalExpenses, type Expense } from './expense'
const sample: Expense[] = [
{ id: 'a', description: 'Bus pass', amount: 125, category: 'travel', date: '2026-10-01' },
{ id: 'b', description: 'Notebook', amount: 40, category: 'study', date: '2026-10-02' },
]
describe('expense rules', () => {
it('rejects a zero amount', () => {
expect(() => createExpense({
description: 'Tea', amount: '0', category: 'food', date: '2026-10-03',
}, 'c')).toThrow('positive')
})
it('sums saved amounts', () => {
expect(totalExpenses(sample)).toBe(165)
})
})| Area | Meets expectations | Needs more work |
|---|---|---|
| Correctness | Validation and totals match written rules | Invalid values can reach saved state |
| Architecture | Rules are separated from UI and storage | Every concern is in one event handler |
| Testing | Boundary cases and storage failures are checked | Only a happy path has an assertion |
| Usability | Fields are labeled and failures have recovery | Errors are visual only or unclear |
| Delivery | Setup, limitations, and next steps are documented | App only runs in the author’s environment |
- Run type checking and the test suite with the project configuration.
- Build the production bundle and resolve build-time errors before deployment.
- Configure environment-specific values in the hosting platform; never ship development secrets.
- Deploy a preview, verify add/list/total/reload flows, and check browser console and network errors.
- Document that data is local to the browser and list the next improvements you would prioritize.
Follow the chosen host’s current deployment guide. Verify the build, environment configuration, and narrow-screen flows after deploy.
Explain JavaScript Fundamentals and Async Work
1. What is the difference between let, const, and var?
Model answer: let and const are block-scoped; const prevents rebinding, not object mutation. var is function-scoped. I default to const and use let when needed.
- What interviewers look for: scope and mutation distinction.
2. How are === and == different?
Model answer: === compares without type coercion; == coerces. I prefer strict equality and explicit conversions.
- What interviewers look for: coercion and trade-offs.
3. What is the difference between null and undefined?
Model answer: undefined often means absent or unassigned; null is an explicit empty value. Use consistent data conventions.
- What interviewers look for: distinction and examples.
4. What is a closure?
Model answer: A closure retains access to its lexical environment, even after the outer function returns; this supports callbacks and encapsulation.
- What interviewers look for: lexical scope and use case.
Functions and asynchronous execution
5. How does this get its value in JavaScript?
Model answer: An ordinary function’s this depends on its call site; an arrow captures it lexically. I inspect how a function is called.
- What interviewers look for: call-site and arrow behavior.
6. What does an async function return?
Model answer: It always returns a promise: returned values fulfill it and thrown errors reject it. await pauses that function, not the runtime.
- What interviewers look for: promise and error semantics.
7. Does fetch reject when the server responds with 404?
Model answer: No. HTTP errors still resolve to a Response, so check response.ok; network failures reject.
- What interviewers look for: HTTP versus network failure.
8. When would you use Promise.all?
Model answer: Use it for independent work when all results are required; it rejects if any input rejects. Use allSettled to inspect outcomes separately.
- What interviewers look for: concurrency and failure behavior.
Discuss State, Modules, and Quality
9. What is the difference between map and forEach?
Model answer: map transforms into a new array; forEach performs side effects without returning a result array.
- What interviewers look for: intent and return behavior.
10. What is immutability, and why can it help?
Model answer: Immutability creates updated values rather than changing observed state, simplifying reasoning; unnecessary copying can cost performance.
- What interviewers look for: benefits and trade-offs.
11. How are ES modules different from CommonJS?
Model answer: ES modules use import/export; CommonJS uses require/module.exports. Follow the project’s configured format.
- What interviewers look for: syntax and project configuration.
12. Why validate data at runtime if TypeScript already checks types?
Model answer: External JSON, forms, and storage can violate static types at runtime; validate them before use.
- What interviewers look for: runtime validation boundaries.
Show How You Make Software Reliable
13. What makes a useful unit test?
Model answer: A useful unit test deterministically checks one observable rule, avoiding private implementation details.
- What interviewers look for: observable behavior and isolation.
14. What would you mock in a test?
Model answer: Mock external boundaries when needed, but keep the logic real; use integration tests for component collaboration.
- What interviewers look for: balanced isolation.
15. How would you debug a report that an expense is missing?
Model answer: Reproduce the issue, trace input through validation and storage, inspect the first incorrect state, then add a regression test.
- What interviewers look for: evidence and regression prevention.
16. How would you improve this project if it became multi-device?
Model answer: Clarify sync needs, add an authorized server API and database, validate requests, and define conflict/offline behavior.
- What interviewers look for: requirements, trust boundaries, and data ownership.
Common Project and Interview Mistakes
Starting with a framework before defining acceptance checks
Why: The project can become polished without solving a clear problem.
Fix: Write a short brief and acceptance criteria before choosing implementation details.
Trusting a TypeScript type for JSON or local storage
Why: Types disappear at runtime and external data can be malformed.
Fix: Validate values at every untrusted boundary before using them.
Using a demo project as if it were secure financial software
Why: Local browser storage lacks server-side controls and reliable recovery.
Fix: State limitations clearly and never store credentials or payment secrets there.
Answering interview questions with definitions only
Why: A memorized phrase does not show applied understanding.
Fix: Give an example, explain a trade-off, and relate it to an implementation choice.
Finish and Present Your Portfolio Project
Practice
Ship a small, explainable expense tracker
- Implement the typed expense domain rules and reject invalid form inputs before persistence.
- Add a replaceable storage adapter that validates loaded data and handles malformed JSON intentionally.
- Write Vitest cases for validation boundaries, totals, sorting, and storage behavior.
- Build an accessible form and list, then verify adding, reloading, and error recovery in a browser.
- Prepare a short walkthrough: requirements, architecture, one trade-off, one bug you fixed, and the next improvement.
Hint: Keep the first version deliberately small. A clearly tested feature is a stronger portfolio signal than an unfinished collection of features.
🎯 Key Takeaways
- ✓Start a project with a user problem, acceptance checks, and explicit limits.
- ✓Separate domain rules, persistence, and UI so each boundary can be tested and replaced.
- ✓TypeScript improves development-time clarity but does not validate runtime data.
- ✓Keep calculations pure, test boundary cases, and state floating-point assumptions honestly.
- ✓A good interview response combines a correct concept, an example, and a trade-off.
- ✓Explain project limitations and next steps rather than presenting a learning demo as production finance software.
Next
What comes next
You have completed the JavaScript track. Continue into full-stack development to build React interfaces, create Node.js APIs, connect a database, test complete flows, and deploy a real application.
Next course · Full-Stack Development with AI →HELP US IMPROVE
How was this lesson?
Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.
Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.
