32 Topics
Chapter•180 Minutes

Top JavaScript Polyfills: Interview Questions and Answers

Master JavaScript polyfills from basic concepts to advanced implementations, including call, apply, bind, map, filter, reduce, forEach, once, debounce, throttle, Promise methods, Object methods, and other commonly asked polyfill coding problems.

Q1: What is a polyfill in JavaScript?

Difficulty:BeginnerTopic:Fundamentals

Answer

A polyfill is a piece of JavaScript code that implements functionality that is missing in an environment. It allows developers to use certain APIs in environments that do not natively support them.

For example, if an environment does not support Array.prototype.myMap, we can implement a custom version that behaves similarly to the native map() method.

if (!Array.prototype.myMap) {
  Array.prototype.myMap = function (callback, thisArg) {
    const result = [];

    for (let i = 0; i < this.length; i++) {
      if (i in this) {
        result.push(callback.call(thisArg, this[i], i, this));
      }
    }

    return result;
  };
}

console.log([1, 2, 3].myMap(n => n * 2));
// [2, 4, 6]

Important points

  • A polyfill implements missing functionality using JavaScript.
  • A polyfill generally aims to reproduce the behavior of a native API, including its edge cases.
  • A polyfill is different from a transpiler. A transpiler transforms source code, whereas a polyfill provides missing runtime functionality.
  • Production polyfills should follow the relevant ECMAScript specification as closely as practical.
Key Takeaways
  • A polyfill supplies missing runtime functionality.

  • Correct polyfills should reproduce native API behavior, not just the simplest use case.

Q2: Implement a polyfill for Array.prototype.map().

Difficulty:BeginnerTopic:Array Methods

Answer

The map() method creates a new array by applying a callback to each existing element of the original array. It does not mutate the original array.

A good polyfill should support the callback arguments value, index, and array, an optional thisArg, and sparse arrays.

Array.prototype.myMap = function (callback, thisArg) {
  if (this == null) {
    throw new TypeError("Array.prototype.myMap called on null or undefined");
  }

  if (typeof callback !== "function") {
    throw new TypeError("Callback must be a function");
  }

  const array = Object(this);
  const length = array.length >>> 0;
  const result = new Array(length);

  for (let i = 0; i < length; i++) {
    if (i in array) {
      result[i] = callback.call(thisArg, array[i], i, array);
    }
  }

  return result;
};

console.log([1, 2, 3].myMap(n => n * 2));
// [2, 4, 6]

How it works

  1. Validate the receiver and callback.
  2. Convert the receiver to an object and capture its length.
  3. Create a result array with the same length.
  4. Visit only indexes that exist in the source array.
  5. Store the callback result at the corresponding index.
  6. Return the new array.

The i in array check preserves holes in sparse arrays. The unsigned right shift used above is a common interview simplification for obtaining a 32-bit unsigned length; it is not fully specification-compliant for every possible array-like object. A production-quality implementation should use LengthOfArrayLike semantics.

Map polyfill usage
const numbers = [1, 2, 3, 4];

const doubled = numbers.myMap((value, index, array) => {
  console.log(index, array === numbers);
  return value * 2;
});

console.log(doubled); // [2, 4, 6, 8]
console.log(numbers); // [1, 2, 3, 4]

The callback receives the current value, index, and original array. The returned array contains transformed values without modifying the original array.

Key Takeaways
  • Map returns a new array and preserves the source array.

  • A robust implementation handles sparse arrays, callback validation, and thisArg.

Q3: Implement a polyfill for Array.prototype.filter().

Difficulty:BeginnerTopic:Array Methods

Answer

The filter() method creates a new array containing the elements for which the callback returns a truthy value.

Array.prototype.myFilter = function (callback, thisArg) {
  if (this == null) {
    throw new TypeError("Array.prototype.myFilter called on null or undefined");
  }

  if (typeof callback !== "function") {
    throw new TypeError("Callback must be a function");
  }

  const array = Object(this);
  const length = array.length >>> 0;
  const result = [];

  for (let i = 0; i < length; i++) {
    if (i in array) {
      const value = array[i];

      if (callback.call(thisArg, value, i, array)) {
        result.push(value);
      }
    }
  }

  return result;
};

console.log([1, 2, 3, 4, 5].myFilter(n => n % 2 === 0));
// [2, 4]

Explanation

Unlike map(), which produces one output slot for every existing input element, filter() only includes elements that pass the condition.

The implementation skips holes in sparse arrays and passes the value, index, and original array to the callback.

Key Takeaways
  • Filter returns a new array containing only matching elements.

  • The callback's truthiness determines whether an element is retained.

Q4: Implement a polyfill for Array.prototype.forEach().

Difficulty:BeginnerTopic:Array Methods

Answer

The forEach() method executes a callback for every existing element in an array. It returns undefined and does not build a result array.

Array.prototype.myForEach = function (callback, thisArg) {
  if (this == null) {
    throw new TypeError("Array.prototype.myForEach called on null or undefined");
  }

  if (typeof callback !== "function") {
    throw new TypeError("Callback must be a function");
  }

  const array = Object(this);
  const length = array.length >>> 0;

  for (let i = 0; i < length; i++) {
    if (i in array) {
      callback.call(thisArg, array[i], i, array);
    }
  }
};

const result = [10, 20, 30].myForEach((value, index) => {
  console.log(index, value);
});

console.log(result); // undefined

Explanation

  • The callback executes for each existing index.
  • The original array is not automatically modified, although the callback can modify it.
  • forEach() cannot be stopped early with break or a callback return value.
  • The iteration length is captured before the loop, matching native behavior more closely than repeatedly reading the length.
Key Takeaways
  • ForEach executes callbacks for side effects and returns undefined.

  • A callback's return value does not control iteration.

Q5: Implement a polyfill for Array.prototype.reduce().

Difficulty:BeginnerTopic:Array Methods

Answer

The reduce() method processes array elements and accumulates them into a single result.

The accumulator starts with the supplied initial value when one is provided. Otherwise, it starts with the first existing array element.

Array.prototype.myReduce = function (callback, initialValue) {
  if (this == null) {
    throw new TypeError("Array.prototype.myReduce called on null or undefined");
  }

  if (typeof callback !== "function") {
    throw new TypeError("Callback must be a function");
  }

  const array = Object(this);
  const length = array.length >>> 0;
  let index = 0;
  let accumulator;

  if (arguments.length >= 2) {
    accumulator = initialValue;
  } else {
    while (index < length && !(index in array)) {
      index++;
    }

    if (index >= length) {
      throw new TypeError("Reduce of empty array with no initial value");
    }

    accumulator = array[index++];
  }

  while (index < length) {
    if (index in array) {
      accumulator = callback(
        accumulator,
        array[index],
        index,
        array
      );
    }

    index++;
  }

  return accumulator;
};

console.log([1, 2, 3, 4].myReduce((sum, n) => sum + n, 0));
// 10

Important interview edge cases

Empty array with an initial value: returns the initial value.

Empty array without an initial value: throws a TypeError.

Array without an initial value: the first existing element becomes the initial accumulator, and iteration starts after that element.

The implementation preserves sparse-array behavior. As with the earlier examples, length >>> 0 is a simplified length conversion rather than an exact implementation of the ECMAScript abstract operations.

Reduce to group objects
const fruits = ["apple", "banana", "apple", "orange", "banana", "apple"];

const counts = fruits.myReduce((result, fruit) => {
  result[fruit] = (result[fruit] || 0) + 1;
  return result;
}, {});

console.log(counts);
// { apple: 3, banana: 2, orange: 1 }

Reduce can build a new object by returning the updated accumulator on each iteration.

Key Takeaways
  • Reduce carries an accumulator across iterations.

  • Without an initial value, an empty array or an array containing only holes throws a TypeError.

Q6: Implement a polyfill for Array.prototype.some().

Difficulty:BeginnerTopic:Array Methods

Answer

The some() method returns true as soon as at least one existing array element satisfies the callback condition. If no element matches, it returns false.

Array.prototype.mySome = function (callback, thisArg) {
  if (this == null) {
    throw new TypeError("Array.prototype.mySome called on null or undefined");
  }

  if (typeof callback !== "function") {
    throw new TypeError("Callback must be a function");
  }

  const array = Object(this);
  const length = array.length >>> 0;

  for (let i = 0; i < length; i++) {
    if (i in array && callback.call(thisArg, array[i], i, array)) {
      return true;
    }
  }

  return false;
};

console.log([1, 3, 5, 8].mySome(n => n % 2 === 0));
// true

Explanation

The method short-circuits on the first matching element. It returns false for an empty array because no element satisfies the condition.

Key Takeaways
  • Some checks whether at least one element matches.

  • It short-circuits and returns a boolean.

Q7: Implement a polyfill for Array.prototype.every().

Difficulty:BeginnerTopic:Array Methods

Answer

The every() method returns true if every existing element satisfies the callback condition. It returns false immediately when an element fails.

Array.prototype.myEvery = function (callback, thisArg) {
  if (this == null) {
    throw new TypeError("Array.prototype.myEvery called on null or undefined");
  }

  if (typeof callback !== "function") {
    throw new TypeError("Callback must be a function");
  }

  const array = Object(this);
  const length = array.length >>> 0;

  for (let i = 0; i < length; i++) {
    if (i in array && !callback.call(thisArg, array[i], i, array)) {
      return false;
    }
  }

  return true;
};

console.log([2, 4, 6].myEvery(n => n % 2 === 0));
// true

Explanation

every() is the logical counterpart of some(). It short-circuits on the first failing element. An empty array returns true, which is known as vacuous truth.

Key Takeaways
  • Every checks whether all existing elements satisfy a condition.

  • Every returns true for an empty array.

Q8: Implement a polyfill for Array.prototype.find().

Difficulty:BeginnerTopic:Array Methods

Answer

The find() method returns the first array element for which the callback returns a truthy value. If no element matches, it returns undefined.

Unlike map(), filter(), and forEach(), find() invokes the callback for every index below the captured length, including holes in sparse arrays. A hole is read as undefined.

Array.prototype.myFind = function (callback, thisArg) {
  if (this == null) {
    throw new TypeError("Array.prototype.myFind called on null or undefined");
  }

  if (typeof callback !== "function") {
    throw new TypeError("Callback must be a function");
  }

  const array = Object(this);
  const length = array.length >>> 0;

  for (let i = 0; i < length; i++) {
    const value = array[i];

    if (callback.call(thisArg, value, i, array)) {
      return value;
    }
  }

  return undefined;
};

console.log([5, 12, 8, 130].myFind(n => n > 10));
// 12

Explanation

The loop stops immediately when a matching element is found. Returning from the function avoids unnecessary callback executions.

Key Takeaways
  • Find returns the first matching value, not an array.

  • Unlike several other array iteration methods, find visits sparse-array indexes as undefined.

Q9: Implement a polyfill for Array.prototype.includes().

Difficulty:IntermediateTopic:Array Methods

Answer

The includes() method checks whether an array contains a value. It uses SameValueZero equality, meaning NaN matches NaN, and positive and negative zero are treated as equal.

Array.prototype.myIncludes = function (searchElement, fromIndex = 0) {
  if (this == null) {
    throw new TypeError("Array.prototype.myIncludes called on null or undefined");
  }

  const array = Object(this);
  const length = array.length >>> 0;

  if (length === 0) {
    return false;
  }

  let index = Number(fromIndex);

  if (Number.isNaN(index)) {
    index = 0;
  }

  index = index < 0 ? Math.ceil(index) : Math.floor(index);

  if (index >= length) {
    return false;
  }

  if (index < 0) {
    index = Math.max(length + index, 0);
  }

  for (let i = index; i < length; i++) {
    const value = array[i];

    if (
      value === searchElement ||
      (value !== value && searchElement !== searchElement)
    ) {
      return true;
    }
  }

  return false;
};

console.log([1, 2, NaN].myIncludes(NaN));
// true

console.log([1, 2, 3].myIncludes(2, -2));
// true

Explanation

The expression value !== value identifies NaN, because NaN is the only JavaScript value that is not equal to itself. This implementation covers common cases, but exact native compatibility requires careful handling of conversions and array-like lengths.

Key Takeaways
  • Includes uses SameValueZero comparison and can find NaN.

  • Negative fromIndex values count backward from the array's length.

Q10: Implement a polyfill for Array.prototype.flat().

Difficulty:IntermediateTopic:Recursion

Answer

The flat() method creates a new array with nested arrays flattened to a specified depth. Its default depth is 1.

Array.prototype.myFlat = function (depth = 1) {
  if (this == null) {
    throw new TypeError("Array.prototype.myFlat called on null or undefined");
  }

  const array = Object(this);
  const result = [];
  const maxDepth = Math.floor(Number(depth));
  const actualDepth = Number.isNaN(maxDepth)
    ? 0
    : Math.max(maxDepth, 0);

  function flatten(items, remainingDepth) {
    for (let i = 0; i < items.length; i++) {
      if (!(i in items)) {
        continue;
      }

      const value = items[i];

      if (Array.isArray(value) && remainingDepth > 0) {
        flatten(value, remainingDepth - 1);
      } else {
        result.push(value);
      }
    }
  }

  flatten(array, actualDepth);
  return result;
};

console.log([1, [2, [3, [4]]]].myFlat(2));
// [1, 2, 3, [4]]

Explanation

The recursive function traverses nested arrays while the remaining depth is greater than zero. It appends non-array values and arrays encountered at the requested depth to the result.

This is an interview-oriented implementation. Native flat() has more detailed coercion rules for depth and supports generic array-like receivers.

Key Takeaways
  • Flat recursively processes nested arrays up to the requested depth.

  • Sparse slots in flattened arrays are skipped.

Q11: How would you flatten an array completely using a polyfill?

Difficulty:IntermediateTopic:Recursion

Answer

To flatten an array to any nesting depth, recursively traverse nested arrays until no nested arrays remain.

function flattenDeep(array) {
  const result = [];

  for (let i = 0; i < array.length; i++) {
    if (!(i in array)) {
      continue;
    }

    const value = array[i];

    if (Array.isArray(value)) {
      result.push(...flattenDeep(value));
    } else {
      result.push(value);
    }
  }

  return result;
}

console.log(flattenDeep([1, [2, [3, [4, 5]]]]));
// [1, 2, 3, 4, 5]

Explanation

This solution uses recursion and the Array.isArray() check. Each nested array is flattened independently, and its result is appended to the parent result.

The spread operator can hit argument-count limits for extremely large arrays. For production code handling large inputs, append elements iteratively instead.

Key Takeaways
  • Deep flattening requires processing nested arrays at every level.

  • Recursion is easy to understand, but iterative implementations can avoid call-stack limits.

Q12: Implement a polyfill for Function.prototype.call().

Difficulty:IntermediateTopic:Function Methods

Answer

The call() method invokes a function immediately with a specified this value and individual arguments.

Function.prototype.myCall = function (thisArg, ...args) {
  if (typeof this !== "function") {
    throw new TypeError("myCall must be called on a function");
  }

  const fn = this;
  const context = thisArg == null ? globalThis : Object(thisArg);
  const key = Symbol("fn");

  context[key] = fn;

  try {
    return context[key](...args);
  } finally {
    delete context[key];
  }
};

function greet(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`;
}

const person = { name: "Suriya" };

console.log(greet.myCall(person, "Hello", "!"));
// Hello, Suriya!

Explanation

  1. Capture the function as this inside myCall.
  2. Convert the supplied receiver into an object, except for nullish values, which use globalThis in this simplified implementation.
  3. Attach the function temporarily under a unique symbol.
  4. Invoke it as a method so the receiver becomes its this value.
  5. Delete the temporary property in a finally block.

Important limitation: This technique is an interview approximation, not a fully specification-compliant polyfill. Native call() treats nullish receivers differently in strict and non-strict functions. This implementation also cannot reproduce every behavior of native call, especially for all exotic receivers and functions.

Key Takeaways
  • Call invokes a function immediately with a specified receiver and separate arguments.

  • Temporary symbol properties are a common interview technique, but not an exact replacement for the native method.

Q13: Implement a polyfill for Function.prototype.apply().

Difficulty:IntermediateTopic:Function Methods

Answer

The apply() method invokes a function immediately with a specified this value and arguments supplied as an array or array-like object.

Function.prototype.myApply = function (thisArg, argsArray) {
  if (typeof this !== "function") {
    throw new TypeError("myApply must be called on a function");
  }

  const fn = this;
  const context = thisArg == null ? globalThis : Object(thisArg);
  const key = Symbol("fn");
  const args = argsArray == null ? [] : Array.from(argsArray);

  context[key] = fn;

  try {
    return context[key](...args);
  } finally {
    delete context[key];
  }
};

function add(a, b, c) {
  return this.base + a + b + c;
}

console.log(add.myApply({ base: 10 }, [1, 2, 3]));
// 16

Explanation

The implementation follows the same temporary-property technique as the call() polyfill. The difference is that apply() accepts a single argument collection instead of separate arguments.

Array.from() supports common array-like objects and iterables. Native apply() has specific behavior for its arguments list and does not simply call Array.from() on every supplied value, so this is an interview-oriented approximation.

Key Takeaways
  • Apply invokes the function immediately with arguments from an array-like collection.

  • Call and apply differ mainly in how their arguments are supplied.

Q14: Implement a polyfill for Function.prototype.bind().

Difficulty:IntermediateTopic:Function Methods

Answer

The bind() method returns a new function that, when called, invokes the original function with a predetermined this value and optionally prepended arguments.

Function.prototype.myBind = function (thisArg, ...boundArgs) {
  if (typeof this !== "function") {
    throw new TypeError("myBind must be called on a function");
  }

  const originalFunction = this;

  function boundFunction(...laterArgs) {
    const isConstructing = new.target !== undefined;
    const receiver = isConstructing ? this : thisArg;

    return originalFunction.apply(receiver, [
      ...boundArgs,
      ...laterArgs
    ]);
  }

  if (originalFunction.prototype) {
    boundFunction.prototype = Object.create(originalFunction.prototype);
    Object.defineProperty(boundFunction.prototype, "constructor", {
      value: boundFunction,
      writable: true,
      configurable: true
    });
  }

  return boundFunction;
};

function introduce(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`;
}

const person = { name: "Suriya" };
const sayHello = introduce.myBind(person, "Hello");

console.log(sayHello("!"));
// Hello, Suriya!

Explanation

  • boundArgs contains arguments provided when myBind() is called.
  • laterArgs contains arguments supplied when the bound function is invoked.
  • The bound function combines both argument lists.
  • When the bound function is invoked as a constructor using new, the new instance becomes the receiver rather than the bound thisArg.

Advanced limitation

A fully compliant native bind() also handles bound-function length and name properties, constructor behavior, and prototype semantics precisely. The implementation above demonstrates the central interview concept but does not reproduce every native edge case.

Partial application
function multiply(a, b, c) {
  return a * b * c;
}

const multiplyByTwo = multiply.myBind(null, 2);
console.log(multiplyByTwo(3, 4)); // 24

Bind can preconfigure arguments as well as a receiver. This is called partial application.

Key Takeaways
  • Bind returns a new function instead of invoking the original immediately.

  • Bound arguments are prepended to arguments passed later, and construction requires special handling.

Q15: Implement a polyfill for Object.assign().

Difficulty:IntermediateTopic:Object Methods

Answer

Object.assign() copies enumerable own properties from one or more source objects into a target object. It returns the target object and performs a shallow copy.

if (!Object.myAssign) {
  Object.myAssign = function (target, ...sources) {
    if (target == null) {
      throw new TypeError("Cannot convert undefined or null to object");
    }

    const output = Object(target);

    for (const source of sources) {
      if (source == null) {
        continue;
      }

      const from = Object(source);

      for (const key of Reflect.ownKeys(from)) {
        const descriptor = Object.getOwnPropertyDescriptor(from, key);

        if (descriptor && descriptor.enumerable) {
          output[key] = from[key];
        }
      }
    }

    return output;
  };
}

const target = { a: 1 };
const source = { b: 2 };

console.log(Object.myAssign(target, source));
// { a: 1, b: 2 }

Explanation

  1. Reject a nullish target.
  2. Convert the target into an object.
  3. Process each source object.
  4. Read its own property keys, including symbols.
  5. Copy enumerable properties to the target.
  6. Return the target object.

Interview notes

Object.assign() is shallow: nested objects remain shared references. It reads source property values and writes to the target, so getters and setters can execute. A production implementation should preserve native error and property-copy semantics carefully.

Key Takeaways
  • Object.assign copies enumerable own properties and returns the target.

  • The copy is shallow, and symbol properties can also be copied.

Q16: Implement a polyfill for Array.from().

Difficulty:IntermediateTopic:Iterables

Answer

Array.from() creates a new array from an iterable or array-like object. It can also map each element through an optional callback.

if (!Array.myFrom) {
  Array.myFrom = function (source, mapFn, thisArg) {
    if (source == null) {
      throw new TypeError("Cannot convert null or undefined to an array");
    }

    if (mapFn !== undefined && typeof mapFn !== "function") {
      throw new TypeError("Mapping function must be callable");
    }

    const result = [];
    const mapper = mapFn === undefined ? null : mapFn;
    let index = 0;

    if (typeof source[Symbol.iterator] === "function") {
      for (const value of source) {
        result.push(
          mapper ? mapper.call(thisArg, value, index) : value
        );
        index++;
      }

      return result;
    }

    const object = Object(source);
    const length = Math.min(
      Math.max(Number(object.length) || 0, 0),
      Number.MAX_SAFE_INTEGER
    );

    for (let i = 0; i < length; i++) {
      const value = object[i];
      result.push(mapper ? mapper.call(thisArg, value, i) : value);
    }

    return result;
  };
}

console.log(Array.myFrom("hello"));
// ["h", "e", "l", "l", "o"]

console.log(Array.myFrom([1, 2, 3], n => n * 2));
// [2, 4, 6]

Explanation

An iterable exposes Symbol.iterator. Examples include strings, arrays, sets, and maps. An array-like object instead exposes a length and indexed properties.

The implementation above demonstrates both paths, but a standards-compliant version must handle length conversion, maximum array length, constructor behavior, and iterator errors precisely.

Key Takeaways
  • Array.from supports iterables and array-like objects.

  • Its optional mapping function transforms elements during array creation.

Q17: Implement a polyfill for Object.create().

Difficulty:IntermediateTopic:Prototypes

Answer

Object.create() creates a new object with a specified prototype. Passing null creates an object with no prototype.

if (!Object.myCreate) {
  Object.myCreate = function (prototype) {
    if (
      prototype !== null &&
      typeof prototype !== "object" &&
      typeof prototype !== "function"
    ) {
      throw new TypeError("Prototype must be an object or null");
    }

    function TemporaryConstructor() {}
    TemporaryConstructor.prototype = prototype;

    const result = new TemporaryConstructor();
    TemporaryConstructor.prototype = null;

    return result;
  };
}

const person = {
  greet() {
    return `Hello, ${this.name}`;
  }
};

const user = Object.myCreate(person);
user.name = "Suriya";

console.log(user.greet());
// Hello, Suriya
console.log(Object.getPrototypeOf(user) === person);
// true

Explanation

The temporary constructor creates an object whose prototype is the specified object. The resulting object inherits properties from that prototype without copying them.

Important limitation

This classic technique does not fully reproduce all native behavior, including the optional property-descriptor argument and some legacy edge cases. It is useful for understanding prototype inheritance in interviews.

Key Takeaways
  • Object.create establishes the prototype of a new object.

  • Prototype inheritance is different from copying an object's properties.

Q18: Implement a polyfill for the instanceof operator.

Difficulty:IntermediateTopic:Prototypes

Answer

The instanceof operator normally checks whether a constructor's prototype appears anywhere in an object's prototype chain.

function myInstanceOf(object, constructor) {
  if (
    (typeof object !== "object" || object === null) &&
    typeof object !== "function"
  ) {
    return false;
  }

  if (typeof constructor !== "function") {
    throw new TypeError("Right-hand side must be callable");
  }

  if (!constructor.prototype || typeof constructor.prototype !== "object") {
    throw new TypeError("Constructor prototype must be an object");
  }

  let current = Object.getPrototypeOf(object);

  while (current !== null) {
    if (current === constructor.prototype) {
      return true;
    }

    current = Object.getPrototypeOf(current);
  }

  return false;
}

function Animal(name) {
  this.name = name;
}

const dog = new Animal("Buddy");

console.log(myInstanceOf(dog, Animal)); // true
console.log(myInstanceOf(dog, Object)); // true
console.log(myInstanceOf({}, Animal)); // false

Explanation

The algorithm starts at the object's immediate prototype and traverses the chain until it finds the constructor's prototype or reaches null.

Important limitation

Native instanceof supports custom behavior through Symbol.hasInstance and has specific semantics for unusual constructors. This implementation covers the conventional prototype-chain case.

Key Takeaways
  • Instanceof normally checks the prototype chain, not an object's constructor property.

  • Custom Symbol.hasInstance behavior is outside this simplified implementation.

Q19: Implement a polyfill for Promise.all().

Difficulty:IntermediateTopic:Promises

Answer

Promise.all() accepts an iterable of promises or other values and returns a promise that fulfills when every input fulfills. Results preserve the original input order, regardless of completion order. It rejects when an input rejects.

if (!Promise.myAll) {
  Promise.myAll = function (iterable) {
    return new Promise((resolve, reject) => {
      let items;

      try {
        items = Array.from(iterable);
      } catch (error) {
        reject(error);
        return;
      }

      const results = new Array(items.length);
      let remaining = items.length;

      if (remaining === 0) {
        resolve(results);
        return;
      }

      items.forEach((item, index) => {
        Promise.resolve(item).then(
          value => {
            results[index] = value;
            remaining--;

            if (remaining === 0) {
              resolve(results);
            }
          },
          reject
        );
      });
    });
  };
}

Promise.myAll([
  Promise.resolve(1),
  2,
  Promise.resolve(3)
]).then(console.log);
// [1, 2, 3]

Explanation

  1. Convert the iterable into an array.
  2. Create a results array with the same number of slots.
  3. Resolve each input using Promise.resolve().
  4. Store each fulfilled value at its original index.
  5. Resolve the outer promise when every input fulfills.
  6. Reject the outer promise if an input rejects.

Interview edge cases

  • An empty iterable produces a fulfilled promise containing an empty array.
  • Non-promise values are accepted.
  • Results preserve input order, not completion order.
  • Native Promise.all() has detailed iterable and constructor semantics that a production-quality polyfill must preserve.
Preserving result order
const first = new Promise(resolve => setTimeout(() => resolve("first"), 100));
const second = Promise.resolve("second");

Promise.myAll([first, second]).then(console.log);
// ["first", "second"]

The second promise can fulfill first, but Promise.all returns values in input order.

Key Takeaways
  • Promise.all fulfills only when every input fulfills and rejects when an input rejects.

  • Result ordering follows input order, not completion order.

Q20: Implement a polyfill for Promise.allSettled().

Difficulty:IntermediateTopic:Promises

Answer

Promise.allSettled() waits until all input promises have settled, whether fulfilled or rejected. It returns an array describing each outcome in the same order as the input.

if (!Promise.myAllSettled) {
  Promise.myAllSettled = function (iterable) {
    return new Promise((resolve, reject) => {
      let items;

      try {
        items = Array.from(iterable);
      } catch (error) {
        reject(error);
        return;
      }

      if (items.length === 0) {
        resolve([]);
        return;
      }

      const results = new Array(items.length);
      let remaining = items.length;

      items.forEach((item, index) => {
        Promise.resolve(item).then(
          value => {
            results[index] = {
              status: "fulfilled",
              value
            };
          },
          reason => {
            results[index] = {
              status: "rejected",
              reason
            };
          }
        ).then(() => {
          remaining--;

          if (remaining === 0) {
            resolve(results);
          }
        });
      });
    });
  };
}

Promise.myAllSettled([
  Promise.resolve("success"),
  Promise.reject("failure")
]).then(console.log);

Expected result

[
  { status: "fulfilled", value: "success" },
  { status: "rejected", reason: "failure" }
]

Explanation

Unlike Promise.all(), this method records rejections instead of rejecting the aggregate promise because an individual input rejects. The returned promise still rejects if the iterable itself cannot be consumed correctly.

Key Takeaways
  • AllSettled records both fulfilled and rejected outcomes.

  • The result array preserves input order and includes a status for every input.

Q21: Implement a polyfill for Promise.race().

Difficulty:IntermediateTopic:Promises

Answer

Promise.race() returns a promise that settles as soon as one of the input promises settles. The first settlement may be either fulfillment or rejection.

if (!Promise.myRace) {
  Promise.myRace = function (iterable) {
    return new Promise((resolve, reject) => {
      let iterator;

      try {
        iterator = iterable[Symbol.iterator]();
      } catch (error) {
        reject(error);
        return;
      }

      try {
        while (true) {
          const step = iterator.next();

          if (step.done) {
            break;
          }

          Promise.resolve(step.value).then(resolve, reject);
        }
      } catch (error) {
        reject(error);
      }
    });
  };
}

Promise.myRace([
  new Promise(resolve => setTimeout(() => resolve("slow"), 200)),
  new Promise(resolve => setTimeout(() => resolve("fast"), 50))
]).then(console.log);
// fast

Explanation

Each input is passed through Promise.resolve(). The first fulfillment or rejection that settles the outer promise determines its outcome. Later settlements have no effect on the already-settled promise.

An empty iterable leaves the returned promise pending forever. Exact native compatibility requires careful handling of iterator closing, constructor semantics, and abrupt completion.

Key Takeaways
  • Promise.race settles according to the first input to settle.

  • The winning input may fulfill or reject, and an empty iterable leaves the promise pending.

Q22: Implement a polyfill for Promise.any().

Difficulty:AdvancedTopic:Promises

Answer

Promise.any() fulfills as soon as any input fulfills. If every input rejects, it rejects with an AggregateError containing the rejection reasons.

if (!Promise.myAny) {
  Promise.myAny = function (iterable) {
    return new Promise((resolve, reject) => {
      let items;

      try {
        items = Array.from(iterable);
      } catch (error) {
        reject(error);
        return;
      }

      const errors = new Array(items.length);
      let remaining = items.length;

      if (remaining === 0) {
        reject(new AggregateError([], "All promises were rejected"));
        return;
      }

      items.forEach((item, index) => {
        Promise.resolve(item).then(
          resolve,
          error => {
            errors[index] = error;
            remaining--;

            if (remaining === 0) {
              reject(new AggregateError(errors, "All promises were rejected"));
            }
          }
        );
      });
    });
  };
}

Promise.myAny([
  Promise.reject("error 1"),
  Promise.resolve("success"),
  Promise.reject("error 2")
]).then(console.log);
// success

Explanation

The first fulfilled input resolves the aggregate promise. Rejections are recorded by input index. Only after every input rejects does the method reject with an AggregateError.

An empty iterable rejects with an AggregateError whose errors collection is empty.

Key Takeaways
  • Promise.any succeeds when the first input fulfills.

  • It rejects with AggregateError only when every input rejects or when the input is empty.

Q23: Implement a polyfill for Promise.prototype.finally().

Difficulty:AdvancedTopic:Promises

Answer

Promise.prototype.finally() registers a callback that runs when a promise settles, whether it fulfills or rejects. Normally, the original value or rejection reason is preserved unless the callback itself throws or returns a rejected promise.

if (!Promise.prototype.myFinally) {
  Promise.prototype.myFinally = function (callback) {
    const PromiseConstructor = this.constructor;

    return this.then(
      value => PromiseConstructor.resolve(
        typeof callback === "function" ? callback() : callback
      ).then(() => value),
      reason => PromiseConstructor.resolve(
        typeof callback === "function" ? callback() : callback
      ).then(() => {
        throw reason;
      })
    );
  };
}

Promise.resolve("success")
  .myFinally(() => console.log("Cleanup"))
  .then(console.log);
// Cleanup
// success

Explanation

The fulfillment handler waits for the cleanup callback and then returns the original fulfillment value. The rejection handler waits for cleanup and then throws the original rejection reason.

If the callback throws or returns a rejected promise, the resulting promise rejects with that new error. Native finally() also has specific handling for non-callable callbacks and promise subclass constructors.

Key Takeaways
  • Finally runs after either fulfillment or rejection.

  • Successful cleanup preserves the original outcome; failed cleanup can replace it.

Q24: Implement a simplified polyfill for Promise.resolve().

Difficulty:IntermediateTopic:Promises

Answer

Promise.resolve(value) returns a promise that adopts the supplied value's state. If the value is a promise or thenable, the returned promise adopts its eventual outcome.

function myPromiseResolve(value) {
  return new Promise(resolve => {
    resolve(value);
  });
}

myPromiseResolve(42).then(console.log);
// 42

myPromiseResolve(Promise.resolve("hello")).then(console.log);
// hello

Explanation

The native promise resolution procedure handles ordinary values, promises, thenables, self-resolution, and exceptions thrown while retrieving or invoking a thenable's then method.

The simplified implementation delegates those behaviors to the native Promise constructor's resolve function instead of reimplementing the entire algorithm.

Interview distinction: This is a wrapper around native promise resolution, not a replacement for the native static method. A full polyfill would also need to respect constructor identity and subclass behavior.

Key Takeaways
  • Promise resolution adopts promises and thenables rather than treating them as ordinary nested values.

  • Using the native constructor delegates the complex resolution procedure to the runtime.

Q25: Implement a once() utility that allows a function to execute only once.

Difficulty:BeginnerTopic:Closures

Answer

A once() utility wraps a function so that its implementation executes at most one time. Subsequent calls return the result from the first execution.

function once(fn) {
  let called = false;
  let result;

  return function (...args) {
    if (!called) {
      called = true;
      result = fn.apply(this, args);
    }

    return result;
  };
}

let count = 0;

const initialize = once(() => {
  count++;
  return "initialized";
});

console.log(initialize()); // initialized
console.log(initialize()); // initialized
console.log(count); // 1

Explanation

A closure stores the called flag and the first result. Once the function has run, subsequent calls skip execution.

The flag is set before calling fn, which prevents reentrant calls from executing it again. In this implementation, if fn throws, later calls will not retry it. That behavior is a deliberate design choice and can be changed if retries are required.

Key Takeaways
  • Once uses a closure to remember whether the wrapped function has executed.

  • The wrapper can preserve the first result and the calling receiver.

Q26: Implement a debounce function from scratch.

Difficulty:IntermediateTopic:Closures and Timers

Answer

Debouncing delays function execution until a specified period has elapsed since the last call. It is useful for search inputs, resize handlers, and other frequently triggered events.

function debounce(fn, delay) {
  let timeoutId;

  return function (...args) {
    const context = this;

    clearTimeout(timeoutId);

    timeoutId = setTimeout(() => {
      fn.apply(context, args);
    }, delay);
  };
}

const search = debounce(query => {
  console.log("Searching for:", query);
}, 300);

search("j");
search("ja");
search("javascript");
// After approximately 300 ms without another call:
// Searching for: javascript

Explanation

Each invocation clears the previous timer and creates a new timer. Only the last scheduled invocation executes if no additional call occurs before the delay expires.

Common interview follow-up

How would you add an immediate execution option? A leading-edge debounce executes on the first call in a burst and suppresses subsequent calls until the waiting period ends. A production-ready debounce utility may also support trailing execution, cancellation, flushing, and return-value handling.

Key Takeaways
  • Debounce postpones execution until calls stop for a specified interval.

  • It is useful when only the latest input matters.

Q27: Implement a throttle function from scratch.

Difficulty:IntermediateTopic:Closures and Timers

Answer

Throttling limits how frequently a function executes. A common leading-edge throttle runs immediately and ignores calls made during the configured interval.

function throttle(fn, delay) {
  let lastExecution = 0;

  return function (...args) {
    const now = Date.now();

    if (now - lastExecution >= delay) {
      lastExecution = now;
      return fn.apply(this, args);
    }
  };
}

const logScroll = throttle(() => {
  console.log("Scroll event handled");
}, 500);

window.addEventListener("scroll", logScroll);

Explanation

The wrapper records the time of the last execution. A new invocation executes only if the configured interval has passed.

This implementation is a basic leading-edge throttle. It does not schedule a trailing invocation, so the last event in a burst may never be processed. A production implementation may support both leading and trailing behavior, timer cleanup, and cancellation.

Key Takeaways
  • Throttle limits execution frequency during repeated calls.

  • Unlike debounce, a leading-edge throttle can execute before the event burst ends.

Q28: Implement a curry() utility in JavaScript.

Difficulty:IntermediateTopic:Functional Programming

Answer

Currying transforms a function that accepts multiple arguments into a sequence of functions, each accepting one or more arguments until enough arguments have been collected.

For a function with three parameters, the curried form may support sum(1)(2)(3).

function curry(fn) {
  function curried(...args) {
    if (args.length >= fn.length) {
      return fn.apply(this, args);
    }

    return function (...nextArgs) {
      return curried.apply(this, [...args, ...nextArgs]);
    };
  }

  return curried;
}

function sum(a, b, c) {
  return a + b + c;
}

const curriedSum = curry(sum);

console.log(curriedSum(1)(2)(3)); // 6
console.log(curriedSum(1, 2)(3)); // 6
console.log(curriedSum(1)(2, 3)); // 6

Explanation

The utility uses fn.length to determine how many declared parameters the original function expects. If the collected argument count is insufficient, it returns another function that gathers additional arguments.

Important limitation

fn.length does not always equal the number of arguments a function logically requires. Default parameters, rest parameters, and functions with unusual signatures can make this approach unsuitable without an explicit arity argument.

Key Takeaways
  • Currying transforms multi-argument calls into chained function calls.

  • Closures retain arguments collected during earlier calls.

Q29: Implement a memoize() utility for caching function results.

Difficulty:IntermediateTopic:Caching

Answer

Memoization caches the result of a function call so repeated calls with the same inputs can reuse the previous result.

function memoize(fn) {
  const cache = new Map();

  return function (...args) {
    const key = JSON.stringify(args);

    if (cache.has(key)) {
      return cache.get(key);
    }

    const result = fn.apply(this, args);
    cache.set(key, result);

    return result;
  };
}

const slowSquare = memoize(n => {
  console.log("Calculating...");
  return n * n;
});

console.log(slowSquare(5)); // Calculates... 25
console.log(slowSquare(5)); // 25, retrieved from cache

Explanation

The wrapper computes a cache key from the arguments. If the key exists, it returns the stored result; otherwise, it calls the original function and caches the result.

Interview edge cases

  • JSON.stringify() can produce collisions for certain inputs and cannot serialize all JavaScript values.
  • Object identity is not preserved by JSON serialization.
  • The receiver, this, may affect the function's result but is not included in the key.
  • Unbounded caches can grow indefinitely.

A production implementation should choose a cache-key strategy appropriate to the function's inputs. For a function that accepts only primitive arguments, a nested Map structure can provide safer key semantics.

Key Takeaways
  • Memoization reuses results for repeated inputs.

  • Cache keys and cache invalidation must be designed carefully.

Q30: Implement a deep-clone utility and explain its limitations.

Difficulty:AdvancedTopic:Recursion and References

Answer

A deep clone creates a separate copy of an object's nested structure rather than sharing nested references with the original.

For supported values, the native structuredClone() API is usually preferable to a hand-written implementation. However, interview questions often ask you to implement a basic deep clone.

function deepClone(value, seen = new WeakMap()) {
  if (value === null || typeof value !== "object") {
    return value;
  }

  if (seen.has(value)) {
    return seen.get(value);
  }

  if (value instanceof Date) {
    return new Date(value.getTime());
  }

  if (value instanceof RegExp) {
    return new RegExp(value.source, value.flags);
  }

  if (value instanceof Map) {
    const clone = new Map();
    seen.set(value, clone);

    for (const [key, item] of value) {
      clone.set(deepClone(key, seen), deepClone(item, seen));
    }

    return clone;
  }

  if (value instanceof Set) {
    const clone = new Set();
    seen.set(value, clone);

    for (const item of value) {
      clone.add(deepClone(item, seen));
    }

    return clone;
  }

  if (Array.isArray(value)) {
    const clone = [];
    seen.set(value, clone);

    for (const key of Reflect.ownKeys(value)) {
      const descriptor = Object.getOwnPropertyDescriptor(value, key);

      if (descriptor && "value" in descriptor) {
        descriptor.value = deepClone(descriptor.value, seen);
      }

      Object.defineProperty(clone, key, descriptor);
    }

    return clone;
  }

  const prototype = Object.getPrototypeOf(value);
  const clone = Object.create(prototype);
  seen.set(value, clone);

  for (const key of Reflect.ownKeys(value)) {
    const descriptor = Object.getOwnPropertyDescriptor(value, key);

    if (descriptor && "value" in descriptor) {
      descriptor.value = deepClone(descriptor.value, seen);
    }

    Object.defineProperty(clone, key, descriptor);
  }

  return clone;
}

const original = {
  user: { name: "Suriya" },
  numbers: [1, 2, 3]
};

const copy = deepClone(original);
copy.user.name = "Alex";

console.log(original.user.name); // Suriya
console.log(copy.user.name); // Alex

Explanation

The WeakMap tracks already-visited objects. This prevents infinite recursion when the input contains circular references and preserves repeated references within the cloned object graph.

The implementation supports ordinary objects, arrays, dates, regular expressions, maps, sets, symbol keys, property descriptors, and circular references. However, it is not a universal cloning algorithm: functions are returned by reference, custom classes and built-in objects may need specialized handling, and objects with internal slots or special construction requirements may not be correctly recreated.

For general-purpose cloning of supported structured-cloneable values, use structuredClone(value) when available.

Key Takeaways
  • Deep cloning separates nested references and must handle cycles when they are possible.

  • A general-purpose clone must account for built-in types, property descriptors, and special object behavior.