JavaScript Project and Interview Prep

Design a typed, tested expense tracker from requirements through deployment, then practice core JavaScript interview questions.

Est. 50 min Updated Suggest a fix
// Part 01 — Project design

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.

Explicit boundaries keep a portfolio project achievable and testable.
RequirementAcceptance checkOut of scope for version one
Add an expenseDescription, category, date, and positive amount are requiredBank account integration
List expensesNewest entries appear first and each has a stable IDMulti-user sharing
Show a totalThe total equals the sum of valid saved amountsCurrency conversion
Keep data locallyReloading the page preserves this browser profile dataCloud synchronization and backups
Handle bad inputInvalid entries are rejected with an actionable messageAdvanced recurring budgets
⚠️ Important
Browser local storage is convenient for a learning project, not a secure financial record system. It is device-local, can be cleared, and is readable by scripts running on the same origin. Do not store credentials or sensitive payment data there.

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.

ModuleResponsibilityDepends on
expense.tsTypes, validation, total and sorting rulesNothing external
expense-storage.tsSerialize, parse, and persist recordsBrowser storage interface
app.tsConnect form events, storage, and renderingDomain and storage modules
*.test.tsVerify rules and boundary behavioursVitest 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.

🎯 Pro Tip
In a portfolio walkthrough, explain one trade-off and its consequence. For example, local-only storage keeps the first version simple but does not support sync or recovery across devices.

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.

expense.ts
typescript
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.

expense.ts
typescript
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.

📌 Real World Example
If a learner adds a ₹125 travel expense and a ₹40 food expense, the displayed total should be derived from the validated records, not typed independently into the page.
// Part 02 — Persistence and UI

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.

expense-storage.ts
typescript
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.

// Part 03 — Tests and delivery

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.

expense.test.ts
typescript
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)
  })
})
Use the rubric to review the project honestly before sharing it.
AreaMeets expectationsNeeds more work
CorrectnessValidation and totals match written rulesInvalid values can reach saved state
ArchitectureRules are separated from UI and storageEvery concern is in one event handler
TestingBoundary cases and storage failures are checkedOnly a happy path has an assertion
UsabilityFields are labeled and failures have recoveryErrors are visual only or unclear
DeliverySetup, limitations, and next steps are documentedApp only runs in the author’s environment
  1. Run type checking and the test suite with the project configuration.
  2. Build the production bundle and resolve build-time errors before deployment.
  3. Configure environment-specific values in the hosting platform; never ship development secrets.
  4. Deploy a preview, verify add/list/total/reload flows, and check browser console and network errors.
  5. 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.

// Part 04 — Interview questions: language and execution

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.
// Part 05 — Interview questions: data and engineering

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.
// Part 06 — Interview questions: design and testing

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.
📌 Real World Example
Interview answers are strongest when you connect a concept to a specific decision from your own project, state the trade-off, and explain what you would change for a different requirement.
// Part 07 — Pitfalls

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.

// Part 08 — Practice

Finish and Present Your Portfolio Project

Practice

Ship a small, explainable expense tracker

  1. Implement the typed expense domain rules and reject invalid form inputs before persistence.
  2. Add a replaceable storage adapter that validates loaded data and handles malformed JSON intentionally.
  3. Write Vitest cases for validation boundaries, totals, sorting, and storage behavior.
  4. Build an accessible form and list, then verify adding, reloading, and error recovery in a browser.
  5. 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.

Choose your feedback

Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.

Share

Discussion

0

Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.

Continue with GitHub
Loading...