DEV Community

KISHAN RAMLAKHAN NISHAD
KISHAN RAMLAKHAN NISHAD

Posted on

call, apply, and bind in a simple way with easy examples

Let’s break down call, apply, and bind in a simple way with easy examples. All three are used to set the value of this in a function, but they work slightly differently.

  1. call()
  • What it does: Calls a function immediately with a specified this value and arguments passed one by one.
  • Syntax:
  • function.call(thisArg, arg1, arg2, ...)
  • Example:
function greet(greeting, punctuation) {
  console.log(`${greeting}, my name is ${this.name}${punctuation}`);
}

const person = { name: "Kishan" };

greet.call(person, "Hello", "!");  
// Output: "Hello, my name is Kishan!"

Enter fullscreen mode Exit fullscreen mode

Key Point:

  • call() immediately executes the function.
  • Pass arguments separately.
  1. apply()
  • What it does: Calls a function immediately with a specified this value and arguments passed as an array.
  • Syntax:
  • function.apply(thisArg, [arg1, arg2, ...])
  • Example:
greet.apply(person, ["Hi", "."]);  
// Output: "Hi, my name is Kishan."

Enter fullscreen mode Exit fullscreen mode

Key Point:
Similar to call(), but you pass arguments as an array.

  1. bind()
  • What it does: Returns a new function with a specified this value. It does not execute the function immediately.
  • Syntax:
  • const newFunction = function.bind(thisArg, arg1, arg2, ...)
  • Example:
const greetKishan = greet.bind(person, "Hey", "!!");

greetKishan();  
// Output: "Hey, my name is Kishan!!"

Enter fullscreen mode Exit fullscreen mode

Key Point:
bind() returns a new function that you can call later.
Useful when you want to save a function with a specific this for later use (e.g., event handlers).

Image description

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more