Search code examples
javascriptfunction-binding

Why does this MDN example use `undefined` in `.bind(undefined, 37)`?


One of the uses of Function.prototype.bind, according to MDN:

The next simplest use of bind() is to make a function with pre-specified initial arguments. These arguments (if any) follow the provided this value and are then inserted at the start of the arguments passed to the target function, followed by the arguments passed to the bound function, whenever the bound function is called.

Question: Why is undefined being bound here? It should be the this value which should have been sent. If the same is happening here, how is undefined an object?

function list() {
  return Array.prototype.slice.call(arguments);
}

var list1 = list(1, 2, 3); // [1, 2, 3]

// Create a function with a preset leading argument.
var leadingThirtysevenList = list.bind(undefined, 37);

var list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]

Solution

  • Why is undefined being bound here?

    Because the value of this inside list doesn't matter (because list doesn't ever reference this) but you have to specify argument 0 as something in order to specify argument 1. In other words, you cannot skip positional arguments.

    how is undefined an object?

    It isn’t. In strict mode, the this value can be specified as any value — object or primitive, including undefined. Outside of strict mode, non-nullish primitives are coerced to objects, i.e. primitives other than null and undefined are wrapped as an object. If null or undefined are specified, this will default to the global object (window in browsers).