DEV Community

Cover image for Learning call, apply, and bind in JavaScript: A Beginner's Guide ๐Ÿš€
Abhinav
Abhinav

Posted on

1

Learning call, apply, and bind in JavaScript: A Beginner's Guide ๐Ÿš€

Understanding how the this keyword works is fundamental in JavaScript. The value of this changes depending on how a function is called. Sometimes, we need to explicitly set this to refer to a specific object. This is where the methods call, apply, and bind come in. These powerful methods let us control the value of this, making them crucial for mastering JavaScript functions and object-oriented programming.

In this blog, weโ€™ll explore these methods in detail and discuss their modern relevance. ๐Ÿ–ฅ๏ธ


What is this in JavaScript? ๐Ÿค”

Before diving into call, apply, and bind, let's briefly discuss this.

this refers to the context in which a function is called. Its value can change depending on how the function is invoked:

  • In a regular function call, this refers to the global object (in browsers, it's window).
  • In a method call, this refers to the object that owns the method.
  • In an event handler, this refers to the DOM element that triggered the event.

Now, letโ€™s see how we can control this context using call, apply, and bind. ๐ŸŒ


1. call Method: Immediate Invocation โšก

The call method allows you to invoke a function and explicitly set the value of this to a specific object. Arguments are passed individually.

Syntax:

func.call(thisArg, arg1, arg2, ...);
Enter fullscreen mode Exit fullscreen mode
  • thisArg: The value you want this to refer to.
  • arg1, arg2, ...: Arguments to pass to the function.

Example:

const person = {
  name: 'Alice',
};

function greet() {
  console.log(`Hello, ${this.name}!`);
}

greet.call(person);  // Output: Hello, Alice!
Enter fullscreen mode Exit fullscreen mode

Why Use call?

call is useful when borrowing methods from one object or when you want to invoke a function immediately with a custom context. ๐Ÿ”„


2. apply Method: Arguments as an Array ๐Ÿ—ฃ๏ธ

The apply method is similar to call, but instead of passing arguments individually, you pass them as an array.

Syntax:

func.apply(thisArg, [arg1, arg2, ...]);
Enter fullscreen mode Exit fullscreen mode
  • thisArg: The value of this.
  • [arg1, arg2, ...]: An array of arguments.

Example:

const person = {
  name: 'Bob',
};

function introduce(greeting, punctuation) {
  console.log(`${greeting}, ${this.name}${punctuation}`);
}

introduce.apply(person, ['Hi', '!']);  // Output: Hi, Bob!
Enter fullscreen mode Exit fullscreen mode

Why Use apply?

apply is useful when you need to pass an array of arguments dynamically. ๐Ÿ“†


3. bind Method: Creating a New Function ๐Ÿ”’

The bind method returns a new function with a fixed this value and optionally preset arguments. Unlike call and apply, it does not invoke the function immediately.

Syntax:

const boundFunc = func.bind(thisArg, arg1, arg2, ...);
Enter fullscreen mode Exit fullscreen mode
  • thisArg: The value of this to bind.
  • arg1, arg2, ...: Optional arguments preset in the bound function.

Example:

const person = {
  name: 'Charlie',
};

function greet() {
  console.log(`Hello, ${this.name}!`);
}

const boundGreet = greet.bind(person);
boundGreet();  // Output: Hello, Charlie!
Enter fullscreen mode Exit fullscreen mode

Why Use bind?

bind is useful when you need to ensure a function always uses a specific context, even if it's passed as a callback (e.g., in event listeners). ๐Ÿ•ฐ


Key Differences Between call, apply, and bind

Feature call apply bind
Invocation Executes the function immediately Executes the function immediately Returns a new function
Arguments Passed individually Passed as an array Passed individually or preset arguments
Use Case Immediate invocation with custom this Invoke with array arguments Create reusable functions with fixed this

When to Use Each Method? ๐Ÿ“œ

  • Use call when invoking a function with a specific this and passing arguments individually. ๐Ÿ”Ÿ
  • Use apply when invoking a function with a specific this and passing arguments as an array. ๐ŸŸ๏ธ
  • Use bind when creating a new function where this is fixed for later use. ๐Ÿ”ง

Are call, apply, and bind Still Relevant in Modern JavaScript? ๐Ÿค”

Modern JavaScript features like arrow functions, the spread/rest syntax, and functional programming paradigms have reduced the need for these methods in some cases. However, call, apply, and bind remain relevant for:

  1. Dynamic Context Binding:

    • Explicitly setting this for borrowed methods or dynamic arguments.
  2. Working with Legacy Code:

    • Older codebases often use these methods extensively.
  3. Function Reusability:

    • Creating reusable functions with specific contexts.

Comparison with Modern Alternatives

  • Arrow Functions: Automatically bind this based on lexical scope but lack the flexibility of manual this control.
  • Spread Syntax (...): Simplifies argument handling but doesn't replace apply for custom contexts.

Example: Spread Syntax vs. apply

const numbers = [1, 2, 3, 4];

// Using apply
const max1 = Math.max.apply(null, numbers);

// Using spread
const max2 = Math.max(...numbers);

console.log(max1 === max2);  // Output: true
Enter fullscreen mode Exit fullscreen mode

Practice Questions ๐Ÿ“

  1. What will be the output of the following code?

    const person = { name: 'John' };
    
    function greet(message) {
      console.log(`${message}, ${this.name}`);
    }
    
    greet.call(person, 'Hello');  // Output?
    
  2. Difference Between call and apply:

    • When would you prefer one over the other? Provide examples.
  3. What is the result of the following code?

    const person = { name: 'Jane' };
    
    function sayHello() {
      console.log(`Hello, ${this.name}`);
    }
    
    const boundSayHello = sayHello.bind(person);
    boundSayHello();  // Output?
    
  4. Can bind pass arguments immediately like call or apply? Why or why not?

  5. Event Handling with bind:

    • Write an example using bind in an event listener.

Conclusion ๐ŸŽ‰

Understanding call, apply, and bind is essential for mastering JavaScript. These methods give you control over the this context, allowing you to write flexible and reusable code. While modern JavaScript has introduced alternatives, these methods remain indispensable in many scenarios. Happy coding! ๐Ÿš€

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

๐Ÿ‘ฅ Ideal for solo developers, teams, and cross-company projects

Learn more

๐Ÿ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay