#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 13 of 50medium

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

Understanding explicit function binding.

What You'll Learn

  • How call, apply, bind work
  • Differences between them
  • Use cases

Comparison

MethodExecutionArguments
call()ImmediateComma-separated
apply()ImmediateArray
bind()Returns new functionComma-separated

Examples

code.jsJavaScript
function greet(greeting, punctuation) {
  console.log(greeting + ', ' + this.name + punctuation);
}

const person = { name: 'John' };

// call - immediate, individual args
greet.call(person, 'Hello', '!');
// 'Hello, John!'

// apply - immediate, array of args
greet.apply(person, ['Hi', '?']);
// 'Hi, John?'

// bind - returns new function
const greetJohn = greet.bind(person, 'Hey');
greetJohn('!'); // 'Hey, John!'

Use Cases

code.jsJavaScript
// Borrowing methods
const arrayLike = { 0: 'a', 1: 'b', length: 2 };
const arr = Array.prototype.slice.call(arrayLike);
// ['a', 'b']

// Max of array
const nums = [1, 5, 3, 9, 2];
Math.max.apply(null, nums); // 9

// Event handlers (preserve this)
class Button {
  constructor() {
    this.clicked = false;
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.clicked = true;
  }
}