AnnotationPrep

JavaScript & TypeScript Edge Cases practice questions

10 questions from the Coding assessment: debugging & verification practice test.

Start practising

JavaScript & TypeScript Edge Cases practice drill

10 scenarios, graded as you go, with the exact grading principle for every answer. Start free, no sign-up.

Sample scenarios

An LLM writes a JavaScript function to sort numbers:

```js
function sortNums(arr) {
return arr.sort();
}
```

What happens when you call `sortNums([10, 2, 1])`?

  1. Returns `[1, 2, 10]`.
  2. Returns `[1, 10, 2]` because `Array.prototype.sort()` converts elements to strings and sorts lexicographically by default, AND mutates `arr` in-place.
  3. Throws a `TypeError` because numbers need a comparator.
  4. Returns `[10, 2, 1]` unchanged.
Show the answer

B. Returns `[1, 10, 2]` because `Array.prototype.sort()` converts elements to strings and sorts lexicographically by default, AND mutates `arr` in-place.

Without a comparator `(a, b) => a - b`, JS `.sort()` sorts by UTF-16 code units (`'10' < '2'`). It also mutates the input array in-place; use `[...arr].sort((a, b) => a - b)`.

Principle: JavaScript Array.prototype.sort Default Behavior

An LLM writes an async loop:

```js
async function fetchAll(ids) {
const out = [];
ids.forEach(async (id) => {
const data = await fetchItem(id);
out.push(data);
});
return out;
}
```

What does `await fetchAll([1, 2, 3])` return?

  1. An array of 3 fetched items in order.
  2. `[]` (an empty array) because `Array.prototype.forEach` does not await async callbacks.
  3. A `Promise` that rejects.
  4. `[undefined, undefined, undefined]`.
Show the answer

B. `[]` (an empty array) because `Array.prototype.forEach` does not await async callbacks.

`forEach` ignores the Promises returned by the async callback and finishes synchronously, so `return out` runs before any `fetchItem` resolves. Use `Promise.all(ids.map(fetchItem))` or a `for...of` loop.

Principle: JavaScript Async: forEach Does Not Await

An LLM writes:

```js
function getTimeout(opts) {
return opts.timeout || 3000;
}
```

If a caller explicitly passes `{ timeout: 0 }` (meaning no timeout), what does `getTimeout` return?

  1. `0`.
  2. `3000`, because `0` is falsy in JavaScript—it should use nullish coalescing (`opts.timeout ?? 3000`).
  3. `undefined`.
  4. `NaN`.
Show the answer

B. `3000`, because `0` is falsy in JavaScript—it should use nullish coalescing (`opts.timeout ?? 3000`).

Using `||` falls back on any falsy value (`0`, `''`, `false`). Nullish coalescing `??` only falls back on `null` or `undefined`, preserving `0`.

Principle: JavaScript Operators: Nullish Coalescing (??) vs OR (||)

Other topics