Skip to the page

Functions and this · core

call, apply and bind

call and apply invoke a function immediately with a chosen this (arguments listed one by one vs as an array), while bind returns a new function with this and any leading arguments fixed.

The notes

What you must know

  • fn.call(thisArg, a, b); fn.apply(thisArg, [a, b]); fn.bind(thisArg, a) returns a new function.
  • Uses: borrowing methods (Object.prototype.toString.call(x), Array.prototype.slice.call(arguments)), Math.max.apply(null, arr) (today Math.max(...arr)), partial application (log.bind(null, 'ERROR')), fixing callbacks.
  • A bound function's this can't be changed again by call, apply or bind. new on a bound function ignores the bound this but keeps the bound arguments.
  • A bound function's name is 'bound fn' and its length is reduced by the number of bound arguments.
  • In sloppy mode a null or undefined thisArg becomes globalThis and primitives are boxed into objects; in strict mode thisArg is used as is.
  • Spreading or applying a huge array can exceed the engine's argument limit (RangeError); use a loop or reduce for very large arrays.

The red pen

Common traps: mistake → fix

  • Mistake: bind calls the function

    Fix: it returns a new function and calls nothing.

  • Mistake: You can re-bind a bound function

    Fix: the first bind wins.

  • Mistake: call and apply treat this differently

    Fix: only the argument format differs.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the difference between call, apply and bind?
  2. Give a real use case for each.
  3. What happens with fn.bind(a).bind(b)? And with new on a bound function?
  4. Write myCall without using call or apply. (see the polyfill lesson)
  5. Why might Math.max.apply(null, hugeArray) throw?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview