Checkpoint: Modern JavaScript
Published by Brayan K
A checkpoint is a hands-on review that combines everything from the modern JavaScript track — template literals, optional chaining, array and object methods, symbols, getters/setters, Proxy, and BigInt — into one build challenge and a short quiz.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Start with invariants, then choose the language features
This checkpoint builds a small in-memory basket model. The useful skill is deciding which guarantees belong at the input boundary, which values are derived, and which objects callers may mutate. Modern syntax only helps after those decisions are clear. There is no network checkout, payment processing or persistence in this exercise.
// Prices are already validated integer hundredths, not decimal Numbers.
const prices = { notebook: 125n, pen: 40n };
const quantities = { notebook: 2, pen: 3 };
// Convert each small integer quantity deliberately before multiplication.
const lines = Object.entries(quantities).map(([id, quantity]) => ({
id, quantity, lineCents: prices[id] * BigInt(quantity)
}));
const total = lines.reduce((sum, line) => sum + line.lineCents, 0n);
console.log(lines.map(line => `${line.id}:${line.lineCents}`).join(", "));
console.log(String(total));
// ✅ Expected output:
// notebook:250, pen:120
// 370The inputs in the worked example are trusted constants. A reusable function must also reject unknown IDs, duplicate catalogue entries and invalid quantities. BigInt & Number Precision owns exact conversion and decimal representation; Object Methods (keys, entries, assign, freeze) owns entry enumeration.
Do not let a convenience default hide invalid data
for (const options of [null, { label: "Supplies" }, { label: "" }]) {
const label = options?.label ?? "Basket";
const valid = typeof label === "string" && label.trim().length > 0;
console.log(JSON.stringify(label), valid);
}
// ✅ Expected output:
// "Basket" true
// "Supplies" true
// "" falseAn empty label is present, so nullish coalescing preserves it and validation rejects it. Replacing it with a fallback would change the contract. Optional Chaining & Nullish Coalescing owns the operator boundaries. In the finished basket, validate the catalogue before publishing a mutable handle. Copy only selected primitive fields so later changes to input objects do not change the prices.
Separate live derived values from detached snapshots
let count = 2;
const model = {
get totalCents() { return BigInt(count) * 125n; },
snapshot() { return { count, totalCents: this.totalCents }; }
};
const before = model.snapshot();
count = 3;
console.log(String(before.totalCents), String(model.totalCents));
console.log(before.count, count);
// ✅ Expected output:
// 250 375
// 2 3This distinction is a feature when named clearly. A total getter is live; a line returned from lines() is a record of one read. Freezing that record protects its own fields. Getters, Setters & Property Descriptors owns accessor behavior; Deep Copy vs Shallow Copy & Data Structures owns deeper copying choices.
Validate every supported route into mutable state
const target = { count: 0 };
const incomplete = new Proxy(target, {
set(object, key, value) {
if (!Number.isInteger(value)) throw new TypeError("integer required");
return Reflect.set(object, key, value);
}
});
Object.defineProperty(incomplete, "count", { value: "not an integer" });
console.log(target.count);
// ✅ Expected output:
// not an integerThe brief deliberately refuses property definitions instead of trying to support every descriptor form. It also refuses unknown properties, deletion, prototype changes and alternate receivers. These limits keep the model small enough to audit. Proxy & Reflect (Metaprogramming) owns the individual trap semantics and their invariants. The model is an application convenience, not an authorization boundary.
let values = ["first", "second"];
const collection = {
[Symbol.iterator]() { return [...values][Symbol.iterator](); }
};
const iterator = collection[Symbol.iterator]();
values.push("third");
console.log([...iterator].join(", "));
console.log([...collection].join(", "));
// ✅ Expected output:
// first, second
// first, second, thirdAn iterator obtained now reads its detached snapshot; a later traversal gets a new snapshot. The symbol selects the standard protocol rather than storing a secret field. Symbols & Well-Known Symbols owns symbol identity, and Iterators & Iterables owns traversal state and completion.
Guided exercise: complete a line-total pipeline
Use the literal hints to select nonzero quantities and multiply in the BigInt domain. This is the calculation stage only; the independent brief adds the input and mutation contracts.
const rows = [
{ quantity: 0, unitCents: 50n },
{ quantity: 2, unitCents: 125n },
{ quantity: 1, unitCents: 40n }
];
const active = rows.filter(row => row.quantity ___ 0); // 👉 replace ___ with >
const totals = active.map(row => row.unitCents * ___(row.quantity)); // 👉 replace ___ with BigInt
const total = totals.reduce((sum, value) => sum + value, ___); // 👉 replace ___ with 0n
console.log(String(total));
// ✅ Expected output:
// 290Build the basket from a written contract
Implement createBasket(items, options = null). Accept a dense catalogue of 1–20 ordinary records with unique lowercase ASCII IDs of 1–12 letters. unitCents must be a BigInt from zero through 1000000000000 inclusive. Copy the selected fields. Options may be nullish or an ordinary non-array object; a nullish label defaults to Basket, otherwise accept a string trimmed to 1–40 UTF-16 code units.
Expose a frozen API with label, quantities, lines(), totalCents and the iterable protocol. Every catalogue quantity starts at zero. Direct writes to known quantity fields accept integers 0–99 and normalize negative zero. Invalid known values throw RangeError. Unknown keys and alternate receivers return false; definition, deletion and prototype-change operations are refused.
lines() returns a fresh array of fresh frozen records for positive quantities, sorted by ASCII ID. Each record contains id, quantity and exact lineCents. totalCents sums those lines. An iterator captures the lines at the time it is requested. Do not mutate input, expose the price Map or claim that freezing the API makes quantities immutable.
function createBasket(items, options = null) {
if (!Array.isArray(items) || items.length < 1 || items.length > 20) throw new TypeError("invalid catalogue");
if (options != null && (typeof options !== "object" || Array.isArray(options))) throw new TypeError("invalid options");
const label = options?.label ?? "Basket";
if (typeof label !== "string" || label.trim().length < 1 || label.trim().length > 40) throw new TypeError("invalid label");
const prices = new Map();
for (let i = 0; i < items.length; i++) {
if (!Object.hasOwn(items, i)) throw new TypeError("catalogue must be dense");
const row = items[i];
if (row === null || typeof row !== "object" || Array.isArray(row) ||
typeof row.id !== "string" || !/^[a-z]{1,12}$/.test(row.id) ||
typeof row.unitCents !== "bigint" || row.unitCents < 0n || row.unitCents > 1000000000000n) {
throw new TypeError("invalid item");
}
if (prices.has(row.id)) throw new TypeError("duplicate item");
prices.set(row.id, row.unitCents);
}
const counts = Object.create(null);
for (const id of prices.keys()) Object.defineProperty(counts, id, {
value: 0, writable: true, enumerable: true, configurable: false
});
Object.preventExtensions(counts);
let quantities;
quantities = new Proxy(counts, {
set(target, key, value, receiver) {
if (receiver !== quantities || !Object.hasOwn(target, key)) return false;
if (!Number.isInteger(value) || value < 0 || value > 99) throw new RangeError("quantity must be an integer from 0 to 99");
return Reflect.set(target, key, value === 0 ? 0 : value, target);
},
defineProperty() { return false; },
deleteProperty() { return false; },
setPrototypeOf() { return false; }
});
function lines() {
return Object.entries(counts)
.filter(([, quantity]) => quantity > 0)
.toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
.map(([id, quantity]) => Object.freeze({
id, quantity, lineCents: prices.get(id) * BigInt(quantity)
}));
}
return Object.freeze({
label: label.trim(),
quantities,
lines,
get totalCents() { return lines().reduce((sum, row) => sum + row.lineCents, 0n); },
[Symbol.iterator]() { return lines()[Symbol.iterator](); }
});
}
const source = [{ id: "pen", unitCents: 40n }, { id: "notebook", unitCents: 125n }];
const cart = createBasket(source, { label: " Supplies " });
source[0].unitCents = 999n;
cart.quantities.pen = 3;
cart.quantities.notebook = 2;
const oldIterator = cart[Symbol.iterator]();
cart.quantities.pen = 1;
const describe = rows => rows.map(row => `${row.id}:${row.quantity}:${row.lineCents}`).join(", ");
console.log(cart.label, describe([...oldIterator]));
console.log(describe(cart.lines()), String(cart.totalCents));
console.log(Reflect.set(cart.quantities, "unknown", 1));
console.log(Reflect.defineProperty(cart.quantities, "pen", { value: 8 }));
try { cart.quantities.pen = 1.5; } catch (error) { console.log(error.name, error.message); }
console.log(cart.quantities.pen, Object.isFrozen(cart));
// ✅ Expected output:
// Supplies notebook:2:250, pen:3:120
// notebook:2:250, pen:1:40 290
// false
// false
// RangeError quantity must be an integer from 0 to 99
// 1 trueBefore comparing with the solution, test a zero-priced item, zero quantities, duplicate IDs, a sparse catalogue, invalid quantity types, detached snapshots and a mutation to the original price object. A successful happy-path total does not establish these invariants. This checkpoint assembles earlier concepts rather than teaching a second version of each owning lesson.
Practice quiz
What does this complete program print? console.log(JSON.stringify(({ label: "" }).label ?? "Basket"));
- ""
- Basket
- undefined
- TypeError
Answer: "". An explicit empty string is preserved; validation is a separate step.
What does this complete program print? console.log(String(125n * BigInt(3)));
- 375n
- 375
- 125125125
- TypeError
Answer: 375. The deliberate BigInt conversion permits exact integer multiplication.
What does this complete program print? let n=1; const x={get total(){return n*2;}}; const before=x.total; n=3; console.log(before,x.total);
- 6 6
- 2 2
- 2 6
- undefined 6
Answer: 2 6. The saved primitive is a snapshot; the getter reads current state.
What does this complete program print? const x=Object.freeze({nested:{n:1}});x.nested.n=2;console.log(x.nested.n);
- 1
- undefined
- TypeError
- 2
Answer: 2. The outer freeze does not make nested state immutable.
What does this complete program print? const x={a:0,b:2};console.log(Object.entries(x).filter(([,n])=>n>0).map(([id])=>id).join(","));
- b
- a,b
- a
- b,a
Answer: b. The filter selects only positive quantities.
What does this complete program print? let values=[1,2];const x={[Symbol.iterator](){return [...values][Symbol.iterator]();}};const it=x[Symbol.iterator]();values.push(3);console.log([...it].join(","));
- 1,2,3
- 1,2
- 3
- TypeError
Answer: 1,2. The iterator owns the array snapshot made when it was requested.
What does this complete program print? const target={n:1};const p=new Proxy(target,{set(){return false;}});console.log(Reflect.set(p,"n",2),target.n);
- true 2
- false 2
- false 1
- true 1
Answer: false 1. The refused write reports false and leaves data unchanged.
What does this complete program print? const rows=[{id:"z"},{id:"a"}];const sorted=rows.toSorted((a,b)=>a.id<b.id?-1:a.id>b.id?1:0);console.log(rows[0].id,sorted[0].id);
- a a
- a z
- z z
- z a
Answer: z a. toSorted returns a new array without reordering the source.
Continue this course
- Previous: BigInt & Number Precision
- Next: Promise Combinators (all, race, allSettled, any) — Coordinate multiple async operations and handle partial failures
- Quick reference: JavaScript cheat sheet