Explain it simply
Explain it simply
Exercise 1 practised one concept at a time. This set mixes two concepts from the Advanced Concepts, OOP and Async JavaScript chapters in each task: closures with higher-order functions, or async/await with loops.
It is like cooking. Frying onions and cooking rice are each easy on their own. Doing both at once means juggling the timing, and something tends to burn. In code, each concept is clear by itself, but the bugs appear where they touch. Spend 10-15 minutes thinking before you look at a solution; challenges like these are also good interview preparation.
Problem → Why → Solution
The problem: each piece is right, the combination is broken
Look at the code below. The object literal, the arrow function, the async function and the try/catch are all valid syntax. Combined, they produce three bugs.
First, count is a public property, so any code can write counter.count = 999. Second, increment is an arrow function, so this is not the counter object. An arrow function takes this from the surrounding code: inside a module that is undefined and you get a TypeError, while in a classic script it quietly turns a global count into NaN. Third, loadUser() returns the promise without await, so the rejection happens after the function has already left its try block. The catch never runs and the result is an unhandled rejection.
const counter = {
count: 0, // anyone can write counter.count = 999
increment: () => this.count++, // arrow function: `this` is not counter
};
async function loadUser(id) {
try {
return fetchUserData(id); // no await: a rejection skips this catch
} catch (err) {
return "Could not load user";
}
}
console.log(loadUser(0)); // Promise { <pending> } - and later an unhandled rejectionWhy are these bugs hard to spot?
None of these traps showed up while each concept was taught on its own: this was taught with method syntax, and try/catch with synchronous code. The bug lives where the rules of two concepts meet, so reading the code one line at a time does not reveal it.
Core concept: inspect the seams between concepts
Before writing an advanced challenge, ask four questions. (1) Who owns the state, and may outside code change it? (2) Which code is synchronous and which is asynchronous? (3) When an error happens, which path does it travel, and who catches it? (4) What does this point to? The answers come straight from each concept's own rules.
| Concept | What it gives you | Trap at the seam |
|---|---|---|
| Closure | Variables that outlive the function call | Using an object property instead loses privacy |
| Static method | Called on the class, no instance needed | this is the class, not an instance |
| async/await | Promise code that reads top to bottom | Without await inside try, catch sees nothing |
| Arrow function | Short, and this comes from outside | As an object method, this is wrong |
Watch the execution order too. All synchronous code runs first; setTimeout callbacks and the code after each await continue later. In the example, loadUser() is awaited at the very end, so the output order matches the code order. If you simply called loadUser(7) without await, the counter and product lines would print first and the user lines would follow about 50ms later.
Finally, put correctness first. Making code shorter or faster is work for after both the success and the failure cases are right.
Actually run the failure path
Call an async task done only after you have run one call that succeeds and one that fails; that is why the example loads both user 7 and user 0. A solution that has only seen the success path may hide a typo in its catch block that nobody has executed yet. Read the error message too: it should tell the user what actually went wrong.
- Ask who owns the state
- Separate sync from async
- Trace where each error travels
- Check what this points to
If you can answer these four questions before typing, more than half the challenge is already solved.
General pattern
function makeThing() { let state = 0; return { change: () => ++state }; } // closure
class Model {
static compare(a, b) { return a.value >= b.value ? a : b; } // on the class itself
}
async function load(id) {
try { return await request(id); } // await INSIDE try, or catch never sees it
catch (err) { return fallback(err); }
}
const names = list.filter(({ key }) => test(key)).map(({ name }) => name);Four shapes: a closure owns private state, a static method lives on the class, the await sits inside try, and filter/map callbacks destructure only the fields they need.
Worked answers to Tasks 1-4
The four tasks: Task 1, write createCounter() with a closure, returning increment(), decrement() and reset(), with count hidden from outside. Task 2, give a Person class (name, age) a static compareAge(p1, p2) that returns the older person. Task 3, call a fetchUserData(id) simulated with setTimeout using async/await and try/catch. Task 4, chain filter and map with destructuring to get the names of products under 1000.
// Task 1: a closure keeps count private
function createCounter() {
let count = 0;
return {
increment: () => ++count,
decrement: () => --count,
reset: () => (count = 0),
};
}
// Task 2: a static method belongs to the class, not to each person
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
static compareAge(p1, p2) {
return p1.age >= p2.age ? p1 : p2; // a tie returns the first person
}
}
// Task 3: a simulated request that can fail
function fetchUserData(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id <= 0) reject(new Error("Invalid user id"));
else resolve({ id, name: "User " + id });
}, 50);
});
}
async function loadUser(id) {
try {
const user = await fetchUserData(id);
return `Loaded ${user.name}`;
} catch (err) {
return `Could not load user ${id}: ${err.message}`;
}
}
// Task 4: destructure inside filter and map
const products = [
{ name: "Pen", price: 500 },
{ name: "Bag", price: 15000 },
{ name: "Book", price: 800 },
];
const counter = createCounter();
console.log(counter.increment(), counter.increment(), counter.decrement());
console.log("after reset:", counter.reset(), "| count visible?", counter.count);
const older = Person.compareAge(new Person("Mya", 31), new Person("Ko Ko", 28));
console.log("older:", older.name);
const cheapNames = products
.filter(({ price }) => price < 1000)
.map(({ name }) => name);
console.log("cheap:", JSON.stringify(cheapNames));
console.log(await loadUser(7));
console.log(await loadUser(0));Code breakdown
- Pre-increment returns the new value
increment: () => ++count,++count returns the value after incrementing, so the first call gives 1 and the second 2; count++ would return the old values 0 and 1. These are arrow functions, but they never use this, so nothing breaks.
- Privacy through the closure
console.log("after reset:", counter.reset(), "| count visible?", counter.count);The returned object has no count property, so counter.count is undefined. Only the three functions can change count.
- A static method decides the tie
return p1.age >= p2.age ? p1 : p2; // a tie returns the first personIt is called on the class as Person.compareAge(). Using >= settles what happens on a tie, and the comment states that choice explicitly.
- await inside try
const user = await fetchUserData(id);Because the await is inside the try block, the rejection for id 0 lands in catch, which returns "Could not load user 0".
- Destructuring in the callbacks
.filter(({ price }) => price < 1000)The callback parameter pulls out only price, so there is no repeated product.price. map() likewise takes only name and produces ["Pen","Book"].
1 2 1
after reset: 0 | count visible? undefined
older: Mya
cheap: ["Pen","Book"]
Loaded User 7
Could not load user 0: Invalid user idSketch the example's timeline
When the output order of an async challenge is unclear, draw a timeline with time flowing from left to right. Put the synchronous lines in the first group, then place setTimeout callbacks and the code after each await later, according to their delays. The diagram below draws the lesson example this way. Notice that loadUser(0) only starts its timer after loadUser(7) has finished, because the two awaits run one after the other.
Execution timeline of the worked example
----------------------------------------
time 0ms --------------------- 50ms --------------------- 100ms
| | |
sync: counter, older, cheap | |
loadUser(7) starts a timer | |
"Loaded User 7" |
loadUser(0) starts a timer |
reject
catch -> messageIn real projects
In real projects
The shapes in these challenges show up in libraries every day. Closure plus higher-order function, as in memoize, caches expensive results. An async loop, as in retry, re-attempts network requests that fail now and then. Static methods often serve as factory methods such as User.fromJSON(data).
In team projects, think about a success test, a failure test and cleanup for every challenge or feature. Code reviews commonly ask whether timers are cleared with clearTimeout, whether event listeners are removed, and whether every promise is returned or awaited. Lint rules such as no-floating-promises (from the TypeScript ESLint plugin) can catch a forgotten await automatically, long before the bug ever reaches a user.
Common mistakes
Common mistakes
Returning a promise from try without await
With return fetchUserData(id), the function hands back the promise immediately and leaves the try block; the later rejection is never seen by catch. Inside try, write return await ... instead.
Writing object methods as arrow functions
Arrow functions have no this of their own. For a method that uses this, write method syntax such as increment() { this.count++; }, or avoid this entirely with a closure variable as this lesson does.
Declaring the memo cache inside the returned function
Writing const cache = new Map() inside the returned function creates a fresh cache on every call, so nothing is ever remembered. The cache must survive between calls, so it belongs in the outer scope, inside memoize itself.
Predicting the wrong output order
Even setTimeout(..., 0) runs its callback only after all the current synchronous code has finished. When predicting output order, separate sync from async instead of reading the code top to bottom.
Mini challenge
Three two-concept challenges
Challenge A: write memoize(fn) with a closure so fn runs once per argument. Challenge B: write retry(task, attempts) as an async loop that re-runs a failing task up to attempts times. Challenge C: write an Inventory class with a private #items field, rest destructuring and a total getter.
- Calling fastSquare(9) twice runs square only once
- retry() logs each failed attempt and throws once attempts run out
- Inventory's add() returns this so calls can be chained
- #items must not show up in Object.keys(shop)
// Challenge A: closure + higher-order function
function memoize(fn) {
// TODO: keep a Map in the closure; return a function (arg) => result
// that calls fn(arg) only the first time it sees arg
}
// Challenge B: async/await + loop + try/catch
async function retry(task, attempts) {
// TODO: for i = 1..attempts, try `return await task(i)`;
// on failure log "attempt i failed: ..." and remember the error
// TODO: after the loop, throw "gave up after N attempts (last message)"
}
// Challenge C: private field + destructuring with rest + getter
class Inventory {
// TODO: a private #items array
add({ name, price, ...details }) {
// TODO: store the item, then return this so calls can be chained
}
get total() {
// TODO: sum every price with reduce
}
namesUnder(limit) {
// TODO: filter by price, then map to names
}
}
// TODO: test memoize with a function that counts its real calls,
// retry with a task that fails twice, and a three-item InventoryExpected: "81 81 16 real calls: 2", two failed-attempt lines then "result: data", two more failures and "final: gave up after 2 attempts (timeout)", then "total: 16300 | under 1000: ["Pen","Book"]" and "private items visible? no".
Show hint
In memoize, test cache.has(arg), not the truthiness of cache.get(arg), because a result could be 0. In retry, return await task(i) inside the loop exits the whole function on the first success. In Inventory's add(), { name, price, ...details } gathers every remaining field into a details object.
Show solution
// Challenge A: closure + higher-order function
function memoize(fn) {
const cache = new Map();
return (arg) => {
if (!cache.has(arg)) cache.set(arg, fn(arg));
return cache.get(arg);
};
}
let slowCalls = 0;
const square = (n) => {
slowCalls++;
return n * n;
};
const fastSquare = memoize(square);
console.log(fastSquare(9), fastSquare(9), fastSquare(4), "real calls:", slowCalls);
// Challenge B: async/await + loop + try/catch
async function retry(task, attempts) {
let lastError;
for (let i = 1; i <= attempts; i++) {
try {
return await task(i); // the await matters: a rejection is caught here
} catch (err) {
lastError = err;
console.log(` attempt ${i} failed: ${err.message}`);
}
}
throw new Error(`gave up after ${attempts} attempts (${lastError.message})`);
}
const flaky = (attempt) =>
new Promise((resolve, reject) =>
setTimeout(() => (attempt < 3 ? reject(new Error("timeout")) : resolve("data")), 10));
console.log("result:", await retry(flaky, 3));
try {
await retry(flaky, 2);
} catch (err) {
console.log("final:", err.message);
}
// Challenge C: class with a private field, destructuring with rest, a getter
class Inventory {
#items = [];
add({ name, price, ...details }) {
this.#items.push({ name, price, details });
return this; // allows chaining
}
get total() {
return this.#items.reduce((sum, { price }) => sum + price, 0);
}
namesUnder(limit) {
return this.#items.filter(({ price }) => price < limit).map(({ name }) => name);
}
}
const shop = new Inventory()
.add({ name: "Pen", price: 500, color: "blue" })
.add({ name: "Bag", price: 15000 })
.add({ name: "Book", price: 800, pages: 120 });
console.log("total:", shop.total, "| under 1000:", JSON.stringify(shop.namesUnder(1000)));
console.log("private items visible?", Object.keys(shop).length === 0 ? "no" : "yes");Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A closure variable is private state that an object property cannot match
- Logic that belongs to no single instance, such as comparison or factories, fits a static method
- Write the await inside try so catch can see the rejection
- Do not use arrow functions for object methods that need this
- Before coding, settle state ownership, sync versus async, error paths and this
MDN — JavaScript Guide — MDN Web Docs