← Back to JavaScript Course | Chapter 6: Functions Advanced | Lesson 4 of 8

JS call apply bind

call()

call() runs a function immediately and lets you set its this value. Arguments are passed one by one. This makes call() convenient when you already know the exact number of arguments a function needs and want to invoke it with a specific this value right away.

Example: call()

javascript
function greet(greeting) {
  console.log(greeting + ", " + this.name);
}
const user = { name: "Sam" };
greet.call(user, "Hello");

apply()

apply() is like call(), but it receives function arguments in an array. apply() is especially useful when you have arguments already collected in an array (or array-like object) and don't want to spread them out manually.

Example: apply()

javascript
function greet(greeting) {
  console.log(greeting + ", " + this.name);
}
const user = { name: "Sam" };
greet.apply(user, ["Hi"]);

bind()

bind() creates a new function with a fixed this value. The new function can be called later. bind() is commonly used to lock in this for a callback that will be invoked later by other code, such as an event handler that needs to reference a specific object instance.

Example: bind()

javascript
function greet() {
  console.log("Hello, " + this.name);
}
const user = { name: "Sam" };
const boundGreet = greet.bind(user);
boundGreet();

Main Difference

call() and apply() run now. bind() returns a new function for later use. Because apply() accepts an array, it also works well with variable-length argument lists where you don't know in advance how many values you're passing.

Example: Main Difference

javascript
function sum(a, b) { return a + b; }
console.log(sum.call(null, 1, 2));   // runs now
console.log(sum.apply(null, [1, 2])); // runs now, args in array
const later = sum.bind(null, 1, 2);
console.log(later());               // runs later

Practice

Use call when arguments are separate, apply when arguments are in an array, and bind when you want a reusable function. A typical pattern is const boundFn = obj.method.bind(obj) so boundFn can be passed around freely without losing its connection to obj.

Example: Practice

javascript
const obj = { value: 42 };
function show() { console.log(this.value); }
const boundFn = show.bind(obj);
boundFn();
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.