JavaScript Snippets
About JavaScript
JavaScript is the core language of the web and a strong tool for scripting and backend development. This track covers modern syntax, async flows, and a mini project.
Set Up a JavaScript Playground
Create a simple workspace for running modern JavaScript in Node.js.
mkdir js-playground
cd js-playground
npm init -y
npm pkg set type=module
node -vObjects, Destructuring, and Template Strings
Use concise syntax to write cleaner, more readable data transforms.
const user = { id: 7, name: 'Ava', role: 'admin' }
const { name, role } = user
console.log(`${name} can access ${role} tools`)
const merged = { ...user, active: true }
console.log(merged)Array map/filter/reduce Pattern
Practice the three most common immutable operations in app code.
const prices = [12, 40, 8, 22]
const discounted = prices.map((p) => p * 0.9)
const overTen = discounted.filter((p) => p > 10)
const total = overTen.reduce((sum, p) => sum + p, 0)
console.log({ discounted, overTen, total })Async/Await with Error Handling
Wrap async network calls in try/catch and return predictable values.
async function loadUsers() {
try {
const res = await fetch('https://jsonplaceholder.typicode.com/users')
if (!res.ok) throw new Error('Request failed')
return await res.json()
} catch (error) {
console.error('loadUsers failed:', error.message)
return []
}
}
loadUsers().then((users) => console.log(users.length))Reusable Debounce Utility
Debounce helps reduce expensive work on rapid input events.
export function debounce(fn, wait = 250) {
let timeoutId
return (...args) => {
clearTimeout(timeoutId)
timeoutId = setTimeout(() => fn(...args), wait)
}
}Mini Project: Expense Tracker Structure
Small project idea: track expenses from the terminal with JSON persistence.
expense-tracker/
src/
commands/addExpense.js
commands/listExpenses.js
storage.js
index.js
data/expenses.jsonMini Project: JSON Storage Module (src/storage.js)
Keep file I/O in one module so command handlers stay focused.
import { readFile, writeFile } from 'node:fs/promises'
const FILE = new URL('../data/expenses.json', import.meta.url)
export async function readExpenses() {
const raw = await readFile(FILE, "utf8")
return JSON.parse(raw)
}
export async function saveExpenses(expenses) {
await writeFile(FILE, JSON.stringify(expenses, null, 2))
}Mini Project: Add Expense Command (src/commands/addExpense.js)
Each command should validate input, then update storage.
import { readExpenses, saveExpenses } from '../storage.js'
export async function addExpense(description, amount) {
const value = Number(amount)
if (!description || Number.isNaN(value)) throw new Error("Invalid input")
const expenses = await readExpenses()
expenses.push({ id: crypto.randomUUID(), description, amount: value })
await saveExpenses(expenses)
}Mini Project: CLI Entrypoint (src/index.js)
Route command-line arguments to feature modules.
import { addExpense } from './commands/addExpense.js'
import { readExpenses } from './storage.js'
const [command, ...args] = process.argv.slice(2)
if (command === 'add') {
await addExpense(args[0], args[1])
} else if (command === 'list') {
console.table(await readExpenses())
} else {
console.log('Usage: node src/index.js <add|list> [...args]')
}Run the Expense Tracker
Use simple scripts while practicing CLI and data persistence.
node src/index.js add "Coffee" 4.5
node src/index.js add "Notebook" 9.99
node src/index.js listNext Learning Upgrades
Use these to continue beyond language basics.
1. Add schema validation with zod or custom guards.
2. Add unit tests for command handlers.
3. Add CSV export support.
4. Add monthly totals and category reports.
5. Add a small browser UI on top of the same logic.