JavaScript Interview Question #114

What do call(), apply(), and bind() do?

Closures, Prototypes, Classes & Advanced Functions Mid-Level Intermediate

Quick Interview Answer

call and apply invoke a function immediately with an explicitly supplied this value. call receives function arguments individually, while apply receives them in an array or array-like collection.

Detailed Explanation

call and apply invoke a function immediately with an explicitly supplied this value. call receives function arguments individually, while apply receives them in an array or array-like collection.

bind does not invoke the function immediately. It returns a new function with this and, optionally, initial arguments preconfigured. These methods are useful when function invocation context must be controlled explicitly.

Code Example

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

const user = { name: "Asif" };

console.log(greet.call(user, "Hello", "!"));
console.log(greet.apply(user, ["Hi", "."]));

const boundGreet = greet.bind(user, "Welcome");
console.log(boundGreet("!"));