Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter and Return Value
3.1.
Syntax: 
3.2.
Parameters:
3.3.
Return Value:
4.
4 Examples 
4.1.
Binding a Method to an Object:
4.2.
JavaScript
4.3.
Partial Application with Bind:
4.4.
JavaScript
4.5.
Event Handlers with Bind:
4.6.
JavaScript
4.7.
Binding Functions in Asynchronous Operations:
4.8.
JavaScript
5.
Frequently Asked Questions 
5.1.
How does _.bind() differ from native JavaScript Function.prototype.bind()?
5.2.
Can the thisArg in _.bind() be changed later?
5.3.
Is _.bind() commonly used in modern JavaScript?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.bind() Method

Author Rinki Deka
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

In JavaScript, ensuring that a function is executed in the correct context (or with the correct this value) can be crucial, especially in object-oriented programming or when dealing with callback functions. 

Lodash _.bind() Method

The Lodash library offers a solution with its _.bind() method. This function creates a new version of a function that, when called, has its this keyword set to a provided value. Additionally, _.bind() can pre-fill a fixed number of arguments, known as partial application. 

Why This Function is Used

The _.bind() function is used to permanently associate a function with a specific context (this value) and optionally with pre-filled arguments. This is particularly useful in scenarios where the context of a function call is dynamic or uncertain, such as event handlers or callbacks in asynchronous operations. By binding a function to a specific object, it ensures consistent execution regardless of how or where the function is called.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax, Parameter and Return Value

Syntax: 

_.bind(func, thisArg, [partials])

Parameters:

  • func (Function): The function to bind.
     
  • thisArg: The value to bind as this.
     
  • [partials]: Arguments to be partially applied (fixed) in the new function.

Return Value:

 (Function) - Returns the new bound function.

4 Examples 

Binding a Method to an Object:

  • JavaScript

JavaScript

var _ = require('lodash');

var user = {

 name: 'John',

 greet: function() {

   console.log('Hello, ' + this.name);

 }

};

setTimeout(_.bind(user.greet, user), 1000);

Output after 1 second:

'Hello, John'


Demonstrates binding a method to its owning object for use with setTimeout.

Partial Application with Bind:

  • JavaScript

JavaScript

function greet(greeting, punctuation) {

 console.log(greeting + ', ' + this.name + punctuation);

}

var greetJohn = _.bind(greet, { name: 'John' }, 'Hello');

greetJohn('!');

Output: 

'Hello, John!'


Shows binding a function with a pre-filled argument.

Event Handlers with Bind:

  • JavaScript

JavaScript

function handleClick(event) {

 console.log(this.label + ' clicked');

}

var button = {

 label: 'Submit',

 onClick: _.bind(handleClick, { label: 'Submit' })

};

document.getElementById('submitButton').addEventListener('click', button.onClick);

// When button is clicked: 
Outputs:

'Submit clicked'


An example of using _.bind() for event handlers to maintain the correct context.

Binding Functions in Asynchronous Operations:

  • JavaScript

JavaScript

var dbQuery = function(callback) {

 // Simulating a database query

 setTimeout(callback, 2000);

};

var logResult = _.bind(function(result) {

 console.log('Query result:', result);

}, null, 'Success');

dbQuery(logResult);

 Output after 2 seconds: 

'Query result: Success'


Demonstrates using _.bind() for handling asynchronous callbacks with pre-filled data.

Frequently Asked Questions 

How does _.bind() differ from native JavaScript Function.prototype.bind()?

Lodash's _.bind() is similar to the native Function.prototype.bind() but has additional capabilities, such as partial application of arguments and better handling of certain edge cases.

Can the thisArg in _.bind() be changed later?

Once a function is bound using _.bind(), the thisArg is permanently fixed and cannot be changed for that bound function.

Is _.bind() commonly used in modern JavaScript?

While _.bind() is still useful, especially for partial application, modern JavaScript arrow functions and their lexical this have reduced the need for explicit binding in many cases.

Conclusion

Lodash's _.bind() method offers a robust way to set the context of a function (this value) and pre-fill arguments, ensuring that the function behaves consistently in various scenarios. It is particularly useful in object-oriented programming and in cases where function context needs to be explicitly controlled.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Lodash _.delay() Method
Next article
Lodash _.bindKey() Method
Live masterclass