SyntaxPilot
Courses/JavaScript Coding Questions/Lesson 20
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

JavaScript Coding Questions · Lesson 20 of 30

Polyfill questions

write your own mapfilter and reduce (empty array and initial value cases)Array.prototype safely

These are the notes for JavaScript Coding Questions, episode 20, interview and placement practice for people who finished the SyntaxPilot JavaScript course. Last episode we wrote our own call, apply and bind. Today: the three polyfill questions that come up in almost every JavaScript interview: write your own map, filter and reduce, with the cases most first attempts get wrong: the index argument, holes in arrays, an empty array, a missing initial value, and an initial value of 0. Then: how to add methods to Array.prototype safely.

Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.

Every program was run with Node.js 24 (node main.js), the SyntaxPilot compiler's JavaScript command, and every output below is real. Plain modern JavaScript, no packages.

First: what is a polyfill?

A polyfill is your own code that does exactly what a built-in method does. Websites ship polyfills so that old browsers, which don't have a newer method yet, still work.

Every array inherits from Array.prototype (its prototype: the object it borrows missing properties from). Put myMap there and every array can call it. Inside it, this is the array it was called on: the object before the dot (episode 19).

Array.prototype.first = function () {
  return this[0];
};
console.log(["chai", "samosa"].first(), [42].first(), [].first());
chai 42 undefined

Q1: Write your own map

Problem. arr.map(fn, thisArg) returns a new array of the same length, where each item is fn(item, index, array). The original array is not changed. thisArg, if given, is this inside fn.

Real life: a canteen's menu card printer. For each dish it prints a new card; the list itself isn't changed. To print 2. samosa it needs the dish and its line number. A blank line stays blank.

Edge cases: callbacks that use the index, an empty array, holes ([10, , 30]), and thisArg.

Attempt: pass only the item

Array.prototype.myMap = function (fn) {
  const result = [];
  for (let i = 0; i < this.length; i++) {
    result.push(fn(this[i]));
  }
  return result;
};
const menu = ["chai", "samosa", "vada pav"];
console.log(menu.myMap((item) => item.toUpperCase()));
console.log(menu.myMap((item, i) => `${i + 1}. ${item}`));
console.log(menu.map((item, i) => `${i + 1}. ${item}`));
const prices = [10, , 30];
console.log(prices.myMap((p) => p * 2), prices.map((p) => p * 2));
[ 'CHAI', 'SAMOSA', 'VADA PAV' ]
[ 'NaN. chai', 'NaN. samosa', 'NaN. vada pav' ]
[ '1. chai', '2. samosa', '3. vada pav' ]
[ 20, NaN, 60 ] [ 20, <1 empty item>, 60 ]
  • We call fn with only the item, so i inside the callback is undefined, and undefined + 1 is NaN.
  • [10, , 30] is a sparse array: index 1 is a hole, a slot that doesn't exist at all (not even as undefined). The real map keeps the hole. Ours read this[1] → undefined, and undefined * 2 → NaN.

Fix: all three arguments, thisArg, and skip holes

Array.prototype.myMap = function (fn, thisArg) {
  const result = new Array(this.length);
  for (let i = 0; i < this.length; i++) {
    if (i in this) {
      result[i] = fn.call(thisArg, this[i], i, this);
    }
  }
  return result;
};
const menu = ["chai", "samosa", "vada pav"];
console.log(menu.myMap((item, i) => `${i + 1}. ${item}`));
const prices = [10, , 30];
console.log(prices.myMap((p) => p * 2), prices.map((p) => p * 2));
console.log([].myMap((x) => x * 2));
const tax = { rate: 0.05, add(p) { return p + p * this.rate; } };
console.log([100, 200].myMap(tax.add, tax));
[ '1. chai', '2. samosa', '3. vada pav' ]
[ 20, <1 empty item>, 60 ] [ 20, <1 empty item>, 60 ]
[]
[ 105, 210 ]
  • new Array(n) makes an array of length n that is all holes; we fill only the slots that exist in the input.
  • i in this is true only if index i really exists in the array (the in operator checks whether a key exists).
  • fn.call(thisArg, …) sets this inside the callback, so tax.add can use this.rate.

Complexity: one pass, O(n) time; a new array of n items, O(n) space (not counting fn's own cost).

Q2: Write your own filter

Problem. arr.filter(fn, thisArg) returns a new array with only the items where fn(item, index, array) is truthy. The result is usually shorter, with no gaps.

Example: keep the canteen prices under ₹100. Edge cases: nothing matches, and filter(Boolean).

Attempt: write to result[i]

Array.prototype.myFilter = function (fn) {
  const result = [];
  for (let i = 0; i < this.length; i++) {
    if (fn(this[i], i, this)) result[i] = this[i];
  }
  return result;
};
const prices = [120, 40, 250, 15, 60];
const cheap = prices.myFilter((p) => p < 100);
console.log(cheap);
console.log(cheap.length, prices.filter((p) => p < 100).length);
[ <1 empty item>, 40, <1 empty item>, 15, 60 ]
5 3

result[i] keeps each item at its old index: 40 was at index 1, so it lands at index 1 and index 0 stays a hole. Filter changes the length, so positions must change too.

Fix: push

Array.prototype.myFilter = function (fn, thisArg) {
  const result = [];
  for (let i = 0; i < this.length; i++) {
    if (i in this && fn.call(thisArg, this[i], i, this)) {
      result.push(this[i]);
    }
  }
  return result;
};
const prices = [120, 40, 250, 15, 60];
const cheap = prices.myFilter((p) => p < 100);
console.log(cheap, cheap.length);
console.log([0, 1, "", "chai", null].myFilter(Boolean));
console.log([].myFilter((p) => p > 0));
[ 40, 15, 60 ] 3
[ 1, 'chai' ]
[]

push always adds at the end, so kept items sit at 0, 1, 2. filter(Boolean) keeps only truthy values: Boolean(x) turns any value into true or false.

Complexity: O(n) time, O(k) space for the k items kept.

Q3: Write your own reduce

Problem. arr.reduce(fn, initial) folds the array into one value. A running value, the accumulator (acc), starts at initial; for each item, acc = fn(acc, item, index, array). If no initial value is given, acc starts as the first item and the loop starts at index 1. An empty array with no initial value throws TypeError: Reduce of empty array with no initial value.

Real life: a canteen cashier's running total: start at 0, add 40, then 25, then 60.

Attempt 1: acc = initial

Array.prototype.myReduce = function (fn, initial) {
  let acc = initial;
  for (let i = 0; i < this.length; i++) {
    acc = fn(acc, this[i], i, this);
  }
  return acc;
};
const bill = [40, 25, 60];
console.log(bill.myReduce((sum, p) => sum + p, 0));
console.log(bill.myReduce((sum, p) => sum + p));
console.log(bill.reduce((sum, p) => sum + p));
125
NaN
125

With no initial value, acc starts as undefined; undefined + 40 is NaN, and NaN plus anything stays NaN.

Attempt 2: if (!initial)

Array.prototype.myReduce = function (fn, initial) {
  let acc = initial;
  let start = 0;
  if (!initial) {
    if (this.length === 0) {
      throw new TypeError("Reduce of empty array with no initial value");
    }
    acc = this[0];
    start = 1;
  }
  for (let i = start; i < this.length; i++) {
    acc = fn(acc, this[i], i, this);
  }
  return acc;
};
const bill = [40, 25, 60];
console.log(bill.myReduce((sum, p) => sum + p));
console.log([].reduce((sum, p) => sum + p, 0));
console.log([].myReduce((sum, p) => sum + p, 0));
125
0
/tmp/main.js:6
      throw new TypeError("Reduce of empty array with no initial value");
      ^

TypeError: Reduce of empty array with no initial value

The real reduce returns 0, ours throws, though we did give an initial value. !initial is true when initial is 0 because 0 is falsy. Falsy values count as false in an if: 0, -0, 0n, "", null, undefined, NaN and false. Our check treated a real 0 as "missing". (The same bug hits "" as the initial value, and false.)

Fix: count the arguments

Array.prototype.myReduce = function (fn, initial) {
  const hasInitial = arguments.length >= 2;
  if (!hasInitial && this.length === 0) {
    throw new TypeError("Reduce of empty array with no initial value");
  }
  let acc = hasInitial ? initial : this[0];
  for (let i = hasInitial ? 0 : 1; i < this.length; i++) {
    acc = fn(acc, this[i], i, this);
  }
  return acc;
};
const bill = [40, 25, 60];
console.log(bill.myReduce((sum, p) => sum + p));
console.log([].myReduce((sum, p) => sum + p, 0));
console.log(bill.myReduce((max, p) => (p > max ? p : max)));
const orders = ["chai", "vada", "chai"];
console.log(orders.myReduce((count, x) => {
  count[x] = (count[x] ?? 0) + 1;
  return count;
}, {}));
[].myReduce((sum, p) => sum + p);
125
0
60
{ chai: 2, vada: 1 }
/tmp/main.js:4
    throw new TypeError("Reduce of empty array with no initial value");
    ^

TypeError: Reduce of empty array with no initial value

arguments.length is how many arguments the caller actually passed. Two or more means an initial value was given, even if it is 0 or undefined. arguments exists only in normal functions; arrow functions don't have it. (?? is the nullish coalescing operator: use the right side only if the left is null or undefined.)

The full version also skips holes, like the real reduce:

Array.prototype.myReduce = function (fn, initial) {
  const hasInitial = arguments.length >= 2;
  let i = 0;
  let acc = initial;
  if (!hasInitial) {
    while (i < this.length && !(i in this)) i++;
    if (i === this.length) {
      throw new TypeError("Reduce of empty array with no initial value");
    }
    acc = this[i++];
  }
  for (; i < this.length; i++) {
    if (i in this) acc = fn(acc, this[i], i, this);
  }
  return acc;
};
console.log([, 5, , 10].myReduce((a, b) => a + b), [, 5, , 10].reduce((a, b) => a + b));
15 15

Complexity: O(n) time, O(1) extra space for the accumulator.

Adding to Array.prototype safely

Array.prototype.myMap = function (fn) {
  return this.map(fn);
};
const menu = ["chai", "samosa"];
for (const i in menu) {
  console.log(i, menu[i]);
}
0 chai
1 samosa
myMap [Function (anonymous)]

for...in visits every enumerable property, including inherited ones. Enumerable means "shows up when you list the keys". Plain assignment creates an enumerable property, so our method leaks into the loop.

Object.defineProperty(Array.prototype, "myMap", {
  value: function (fn, thisArg) {
    const result = new Array(this.length);
    for (let i = 0; i < this.length; i++) {
      if (i in this) result[i] = fn.call(thisArg, this[i], i, this);
    }
    return result;
  },
  writable: true,
  configurable: true,
  enumerable: false,
});
const menu = ["chai", "samosa"];
for (const i in menu) console.log(i, menu[i]);
console.log(menu.myMap((m) => m.length));
if (!Array.prototype.map) console.log("would add map");
else console.log("map exists: leave it alone");
0 chai
1 samosa
[ 4, 6 ]
map exists: leave it alone
  • Object.defineProperty creates a property with exact settings: enumerable: false hides it from loops; writable and configurable match the built-ins.
  • A real polyfill adds a method only if it's missing, and never overwrites a built-in.
  • Changing the prototypes of built-in objects in app code is called monkey patching: avoid it outside polyfills. And loop over arrays with for...of, not for...in.

Complexity summary

Method Time Extra space
myMap O(n) O(n): the new array
myFilter O(n) O(k): the k kept items
myReduce O(n) O(1): the accumulator

Common mistakes (and the exact outputs)

Mistake Code What you see Why Fix
No index in map result.push(fn(this[i])) 'NaN. chai' the callback gets only the item fn.call(thisArg, this[i], i, this)
Holes become values no i in this check [ 20, NaN, 60 ] a hole reads as undefined if (i in this)
result[i] in filter result[i] = this[i] [ <1 empty item>, 40, … ], length 5 keeps the old positions result.push(this[i])
No initial value let acc = initial NaN acc starts as undefined start from this[0], loop from 1
if (!initial) [].myReduce(fn, 0) TypeError: Reduce of empty array with no initial value 0 is falsy arguments.length >= 2
Arrow function as the polyfill Array.prototype.x = () => this… this is not the array arrows have no own this (or arguments) a normal function
Plain assignment to the prototype Array.prototype.myMap = … myMap in for...in it's enumerable Object.defineProperty, enumerable: false

Mini project: a canteen bill with your own methods

Chain all three polyfills to build a bill: drop sold-out items, add GST to each price, and total it.

Array.prototype.myMap = function (fn, thisArg) {
  const r = new Array(this.length);
  for (let i = 0; i < this.length; i++) if (i in this) r[i] = fn.call(thisArg, this[i], i, this);
  return r;
};
Array.prototype.myFilter = function (fn, thisArg) {
  const r = [];
  for (let i = 0; i < this.length; i++) if (i in this && fn.call(thisArg, this[i], i, this)) r.push(this[i]);
  return r;
};
Array.prototype.myReduce = function (fn, initial) {
  const has = arguments.length >= 2;
  if (!has && this.length === 0) throw new TypeError("Reduce of empty array with no initial value");
  let acc = has ? initial : this[0];
  for (let i = has ? 0 : 1; i < this.length; i++) acc = fn(acc, this[i], i, this);
  return acc;
};
const order = [
  { item: "masala chai", price: 20, inStock: true },
  { item: "paneer roll", price: 90, inStock: false },
  { item: "vada pav", price: 25, inStock: true },
  { item: "cold coffee", price: 60, inStock: true },
];
const lines = order
  .myFilter((o) => o.inStock)
  .myMap((o, i) => ({ n: i + 1, item: o.item, withGst: Math.round(o.price * 1.05) }));
lines.forEach((l) => console.log(`${l.n}. ${l.item.padEnd(12)} Rs ${l.withGst}`));
console.log("Total: Rs", lines.myReduce((sum, l) => sum + l.withGst, 0));
console.log("Empty order total: Rs", [].myReduce((sum, l) => sum + l.withGst, 0));
1. masala chai  Rs 21
2. vada pav     Rs 26
3. cold coffee  Rs 63
Total: Rs 110
Empty order total: Rs 0

The empty order works because we pass 0 and count arguments instead of testing !initial.

Your turn: myFind and mySome (solution)

Problem. myFind(fn) returns the first item where fn is truthy, or undefined. mySome(fn) returns true as soon as one item matches, and false for an empty array. Both stop early. Small surprise: find visits holes (as undefined), some skips them.

Array.prototype.myFind = function (fn, thisArg) {
  for (let i = 0; i < this.length; i++) {
    if (fn.call(thisArg, this[i], i, this)) return this[i];
  }
  return undefined;
};
Array.prototype.mySome = function (fn, thisArg) {
  for (let i = 0; i < this.length; i++) {
    if (i in this && fn.call(thisArg, this[i], i, this)) return true;
  }
  return false;
};
const prices = [120, 40, 250, 15];
console.log(prices.myFind((p) => p < 50), prices.find((p) => p < 50));
console.log(prices.myFind((p) => p > 999));
console.log(prices.mySome((p) => p > 200), [].mySome(() => true));
let visits = 0;
[1, , 3].myFind(() => { visits++; return false; });
let someVisits = 0;
[1, , 3].mySome(() => { someVisits++; return false; });
console.log(visits, someVisits);
40 40
undefined
true false
3 2

Practice questions (with solutions)

1. myForEach and myEvery.

Solution
Array.prototype.myForEach = function (fn, thisArg) {
  for (let i = 0; i < this.length; i++) {
    if (i in this) fn.call(thisArg, this[i], i, this);
  }
};
Array.prototype.myEvery = function (fn, thisArg) {
  for (let i = 0; i < this.length; i++) {
    if (i in this && !fn.call(thisArg, this[i], i, this)) return false;
  }
  return true;
};
["chai", "poha"].myForEach((x, i) => console.log(i, x));
console.log([20, 40].myEvery((p) => p < 50), [20, 90].myEvery((p) => p < 50), [].myEvery(() => false));
0 chai
1 poha
true false true

forEach returns undefined (it's only for side effects). every on an empty array is true: no item breaks the rule.

2. myFlat(depth = 1).

Solution
Array.prototype.myFlat = function (depth = 1) {
  const result = [];
  for (let i = 0; i < this.length; i++) {
    if (!(i in this)) continue;
    const x = this[i];
    if (Array.isArray(x) && depth > 0) result.push(...x.myFlat(depth - 1));
    else result.push(x);
  }
  return result;
};
const nested = [1, [2, [3, [4]]], , 5];
console.log(nested.myFlat(), nested.flat());
console.log(nested.myFlat(Infinity));
[ 1, 2, [ 3, [ 4 ] ], 5 ] [ 1, 2, [ 3, [ 4 ] ], 5 ]
[ 1, 2, 3, 4, 5 ]

Like the real flat, holes are removed. Infinity - 1 is still Infinity, so myFlat(Infinity) flattens everything.

3. myReduceRight.

Solution
Array.prototype.myReduceRight = function (fn, initial) {
  const has = arguments.length >= 2;
  if (!has && this.length === 0) throw new TypeError("Reduce of empty array with no initial value");
  let i = this.length - 1;
  let acc = has ? initial : this[i--];
  for (; i >= 0; i--) acc = fn(acc, this[i], i, this);
  return acc;
};
console.log(["a", "b", "c"].myReduceRight((s, x) => s + x));
console.log(["a", "b", "c"].myReduceRight((s, x) => s + x, ">"));
cba
>cba

4. Write map and filter using only reduce.

Solution
const mapR = (arr, fn) => arr.reduce((acc, x, i) => (acc.push(fn(x, i, arr)), acc), []);
const filterR = (arr, fn) => arr.reduce((acc, x, i) => (fn(x, i, arr) && acc.push(x), acc), []);
console.log(mapR([1, 2, 3], (x) => x * 10));
console.log(filterR([5, 12, 8, 30], (x) => x > 10));
[ 10, 20, 30 ]
[ 12, 30 ]

The comma operator (a, b) runs a, then returns b, so each step returns the accumulator.

5. Predict: what does this print, and why?

const arr = [1, 2, 3];
const out = arr.map((x) => {
  arr.push(x * 10);
  return x;
});
console.log(out, arr.length);
Answer
[ 1, 2, 3 ] 6

map reads the length once, at the start, so items pushed during the loop are not visited. Our myMap loops to this.length, which grows: it would never stop on this input. To match the real map, save const len = this.length before the loop.

Quick quiz

const a = [5, 10, 15];
const x = a.reduce((acc, n) => acc + n, "");
const y = a.filter((n) => n > 5).map((n, i) => i);
console.log(x, y);

A) 30 [1, 2] B) 51015 [0, 1] C) 30 [0, 1] D) 51015 [1, 2]

Answer

B, output 51015 [ 0, 1 ]. The initial value "" is a string, so + joins: "5", "510", "51015". filter returns a new array [10, 15], so map sees the new indexes 0 and 1.

Interview questions

  1. What is a polyfill? Code that implements a built-in feature for environments that don't have it yet.
  2. What arguments does the map callback get? (item, index, array), with this = the optional thisArg.
  3. How do you tell "no initial value" from "initial value undefined" in reduce? arguments.length, not the value.
  4. What does [].reduce(fn) do? Throws TypeError: Reduce of empty array with no initial value.
  5. What is a sparse array / a hole? An array with missing indexes, like [1, , 3]; map keeps holes, filter/forEach/reduce skip them.
  6. Why not use an arrow function for the polyfill? It has no own this (so it can't see the array) and no arguments.
  7. Why Object.defineProperty instead of Array.prototype.x = …? To make it non-enumerable, so it doesn't appear in for...in.
  8. Should apps modify built-in prototypes? Only for real polyfills, and only when the method is missing. Otherwise it's monkey patching and can clash with future JavaScript.
  9. Time complexity of map, filter, reduce? All O(n); space O(n), O(k), O(1).

Glossary

Term Meaning
Polyfill Your own code that does exactly what a built-in method does
Array.prototype The object every array inherits methods from
Prototype The object another object inherits missing properties from
this (in a method) The object the method was called on: here, the array
Callback A function you pass to another function to be called by it
thisArg The optional argument that becomes this inside the callback
fn.call(obj, …) Call fn with this = obj (episode 19)
Sparse array An array with holes, like [10, , 30]
Hole An index that doesn't exist at all (shown as <1 empty item>)
in operator i in arr is true if index (key) i exists
new Array(n) An array of length n with only holes
Truthy / falsy Values that count as true / false in an if; falsy: 0, -0, 0n, "", null, undefined, NaN, false
Boolean(x) Turns any value into true or false
Accumulator The running value in reduce
Initial value The accumulator's starting value (reduce's second argument)
arguments An array-like object of all arguments a normal function received
?? Nullish coalescing: use the right side if the left is null/undefined
Enumerable A property that shows up when keys are listed (for...in, Object.keys)
Object.defineProperty Creates a property with exact settings (enumerable, writable…)
for...in Loops over enumerable keys, including inherited ones
for...of Loops over an array's values; the right loop for arrays
Monkey patching Changing built-in objects at run time
Comma operator (a, b) runs a, then returns b
Big-O How the work grows with the input size

Summary

  • A polyfill re-creates a built-in; inside a method on Array.prototype, this is the array.
  • map calls fn.call(thisArg, item, index, array) for each existing index (i in this) and returns a new array of the same length.
  • filter pushes the kept items: no gaps, a shorter array.
  • reduce starts from the first item when there's no initial value, and throws on an empty array; detect "no initial value" with arguments.length, because 0 and "" are falsy.
  • Add to prototypes with Object.defineProperty and enumerable: false, only if the method is missing.
  • Next episode: promise questions I: sleep, retry and timeout with Promise.race.