0
0
JavascriptHow-ToBeginner · 3 min read

How to Use bind in JavaScript: Syntax, Examples, and Tips

In JavaScript, bind creates a new function with a fixed this value and optional preset arguments. It is used to control the context of this inside functions, especially when passing them around or using callbacks.
📐

Syntax

The bind method is called on a function and returns a new function with this set to the provided value. You can also preset arguments that will be passed when the new function is called.

  • func.bind(thisArg[, arg1[, arg2[, ...]]])
  • func: The original function to bind.
  • thisArg: The value to use as this inside the new function.
  • arg1, arg2, ...: Optional arguments to prepend when calling the new function.
javascript
function greet(greeting, punctuation) {
  console.log(greeting + ', ' + this.name + punctuation);
}

const person = { name: 'Alice' };

const greetAlice = greet.bind(person, 'Hello');
💻

Example

This example shows how bind fixes the this value to an object and presets the first argument. Calling the new function prints a greeting using the bound context and argument.

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

const person = { name: 'Alice' };

const greetAlice = greet.bind(person, 'Hello');

greetAlice('!');
Output
Hello, Alice!
⚠️

Common Pitfalls

One common mistake is expecting bind to change the original function's this permanently. It actually returns a new function and does not modify the original. Another pitfall is forgetting to call the bound function, which means no output occurs.

Also, using bind on arrow functions has no effect because arrow functions do not have their own this.

javascript
const obj = { name: 'Bob' };

function sayName() {
  console.log(this.name);
}

const boundSayName = sayName.bind(obj);

// Wrong: forgetting to call the function
// boundSayName;

// Right: call the bound function
boundSayName();
Output
Bob
📊

Quick Reference

UsageDescription
func.bind(thisArg)Returns a new function with this set to thisArg.
func.bind(thisArg, arg1, arg2)Returns a new function with this set and preset arguments.
boundFunc()Calls the new function with bound this and arguments.
Using bind on arrow functionsNo effect because arrow functions inherit this from their scope.

Key Takeaways

bind creates a new function with a fixed this context.
You can preset arguments when binding a function.
The original function is not changed by bind.
Always call the bound function to see the effect.
bind does not work on arrow functions for changing this.