FrontendInterviews.dev

Loading problem…

40. Function.prototype.apply

Easy•
Acceptance: 46.51%
•
🔓3/3 Pro unlocks today

Implement your own version of Function.prototype.apply.

The apply method calls a function with a given this value and arguments provided as an array (or array-like object).

Requirements

1) Core Behavior

Your implementation must:

  • Accept a thisArg parameter to be used as the function's this
  • Accept an argsArray parameter containing arguments
  • Invoke the function using the provided thisArg
  • Return the function's return value

2) Edge Cases

You must correctly handle:

  • null or undefined as thisArg (default to globalThis)
  • Primitive thisArg values (must be boxed to objects)
  • Missing/null/undefined argsArray (treat as empty list)
  • Array-like argsArray objects (e.g. arguments, {0: 'a', length: 1})
  • Invalid argsArray (must throw TypeError)
  • Functions that throw (must not leak temporary properties)
  • Arrow functions (note: arrow functions ignore dynamic this)

Testing Note

Some hidden tests express “expected to throw” using an output marker like:

throwError("TypeError")
throwError("Error") // any Error subtype

Example

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

const person = { name: "Alice" };

greet.myApply(person, ["Hello", "!"]);
// "Hello, Alice!"

Constraints

  • Must not use native call/apply internally
  • If argsArray is null/undefined, treat it as an empty list
  • argsArray may be array-like (e.g. arguments, {0:'a', length:1})
  • If argsArray is provided and is not an object/function, throw TypeError
  • null/undefined thisArg defaults to globalThis
  • Primitive thisArg values must be boxed (Object(thisArg))
  • Must clean up temporary property even if function throws
  • Return value must match native apply behavior