What is the reason behind .bind() adding the optional arguments at the beginning?

My first encounter with .bind() left me puzzled by the fact that the optional arguments passed to the bound function are prepended. This issue arose when I was attempting to delegate tasks to anonymous event handling functions, similar to this:

$('#example').on('change', function(arg1, arg2, evt) {
    console.log(evt, arg1, arg2);
}.bind(null, arg1, arg2));

The MDN reference page for .bind() mentions the preppending multiple times but does not explain why. It has left me wondering - why do I need to place arg1 and arg2 before evt in the function arguments? Wouldn't it be more intuitive and potentially faster if they were appended instead?

Answer №1

In the scenario where additional bound parameters were appended to the call time arguments, the resulting behavior would unfold as follows:

function foo(bar, baz) {}
const b = foo.bind(null, 42);

b();          // bar = 42
b('c');       // bar = 'c', baz = 42
b('c', 'd');  // bar = 'c', baz = 'd'

This means that it becomes uncertain where your bound arguments will be placed, which can be considered somewhat nonsensical.

On the other hand, if you consider bind as a form of partial application or currying, then prepending makes more sense: essentially, foo.bind(null, 42) gives you a partially applied function,
turning a -> b -> c (a function that takes two values and produces a third)
into b -> c (a function that only requires one more value and returns another).

Answer №2

bind() creates a fresh function that, when called, triggers the function on which .bind() is invoked.

For the purpose of this explanation, let's call the function you utilize in your code as f:

var g = function f(arg1, arg2, evt) {
    console.log(evt, arg1, arg2);
}.bind(null, arg1, arg2)

bind() generates a new function (saved in variable g) that accepts any number of arguments (one in this instance).
g can be invoked with no arguments or multiple arguments.

The only mandatory argument for bind() is the object to be referred to as this within the function produced by bind(). The other arguments passed to bind(), if provided, are always accessible in g.

In this case, those additional arguments are arg1 and

arg2</code, which are consistently handed over to <code>f
. When g is invoked, its arguments become the parameters of f; they could be absent, singular, or multiple.

Placing arg1 and arg2 at the start of the call to

f</code, followed by the rest of the arguments sent to <code>g
, is the logical choice.

If arg1 and arg2 are positioned as the final arguments to f</code, then within <code>f you would need to inspect arguments.length to locate the last two arguments, resulting in more complex code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Take charge of JavaScript over CSS using Flash technology

Optimal scenario/arrangement: Imagine a webpage with one Flash movie and a separate section containing several hyperlinks. Each of these hyperlinks is given a distinct class name, like this: Copy code <ul> <li><a href="" class="randomna ...

Capture selected items from checkboxes and incorporate them into the CSS styling

I would like to give users the ability to choose from a series of checkboxes with additional options to add to their CSS. Using JavaScript, I am searching for checked boxes, extracting their names, adding them to a list, and then inserting that list into ...

JavaScript, JQuery, and the Observer Design Pattern

Currently, I am in the process of developing a third-party application specifically for certain websites using Jquery. Lately, I have incorporated rx.Observable into my project. However, grasping the utilization of this new JS library has proven to be qui ...

jsonAn error occurred while attempting to access the Spotify API, which resulted

Currently, I am working on acquiring an access Token through the Client Credentials Flow in the Spotify API. Below is the code snippet that I have been using: let oAuthOptions = { url: 'https://accounts.spotify.com/api/token', method: ' ...

What is the best way to deactivate buttons with AngularJS?

I have a situation where I need to disable the save button in one function and permanently disable both the save as draft and save buttons in another function using AngularJS. How can I accomplish this task with the disable functionality in AngularJS? Her ...

Collaborate using JavaScript SDK V2 to share folders on Dropbox

I am currently working on integrating a service into my Angular 2 application that interacts with the Dropbox service using Javascript SDK V2. Here is how my model is structured: User creates a folder containing photos -> user shares the folder within ...

jQuery Files in Conflict

The issue I am facing involves the code below. The first function requires linked js and css, while the second one needs a jQuery and javascript file inherited from base.html. However, there seems to be a conflict in loading these files (possibly because o ...

Documenting React Native Components: Best Practices and Tips

How can I add comments to a React Component? import React, { useState } from 'react'; import { Text, TextInput, View } from 'react-native'; import PropTypes from "prop-types"; const PizzaTranslator = ({ pizzaEmoji = ' ...

Error message: The property or method "Name" is not defined on this object, but it is being referenced during the rendering process

Currently facing a challenge in implementing the modal closure functionality within the Vue.js template. Take a look at the code snippet: var modalInstance = new Vue({ el: "#modalInstance", data: { displayModal: false } }); Vue.compo ...

Guy discussing the ins and outs of JavaScript variables

I am facing an issue with retrieving the value in the jQuery script. The value should be taken from route_path_images, but it's not showing up. var route_path_images="http://www.domain.com" jQuery("#header_background_night_star").fadeIn(2000).css("b ...

JavaScript has hindered cross-origin response due to Cross-Origin Read Blocking (CORB)

I am having trouble retrieving JSON responses from an API. The error message "Cross-Origin Read Blocking (CORB) blocked cross-origin response" keeps popping up. I've tried searching online for a solution to this problem, but so far, I haven't bee ...

Django Website Experiencing Issues with Google Analytics Integration

I implemented google analytics by inserting the tracking script tag and code at the bottom of the head section in my base.html template which serves as the foundation for all other pages. Additionally, I set up 2 click events to track when users click on ...

receiving a pair of components instead of just one

Here is the code for router.js: import React from 'react'; import { Route } from 'react-router-dom'; import CommentList from './containers/commentview'; import CommentDetalList from './containers/commentdetailview'; ...

Issue with PHP retrieving initial value of post data

Hi there, I am facing an issue with my PHP code where the first value of the input field is not being displayed. However, when I check the console.log, it shows correctly. Here is my console.log output: https://i.sstatic.net/eZvg6.png PHP Output: https ...

Determining focus on file picker dialogue using JavaScript

In my table, each row contains one or more user inputs with a focusout event listener attached to call a function: function inputFocusOut(event, el) { let row = el.closest('tr'); let curFocus = event.relatedTarget; let moveOn = tru ...

Error: The JSONP request encountered an unexpected token, causing a SyntaxError

Asking for data using AJAX: $.getJSON('https://www.cryptocompare.com/api/data/coinsnapshot/?fsym=BTC&tsym=USD&callback=?', function(result) { console.log(result); }); Encountering an error: "Uncaught SyntaxError: Unexpected token :" ...

Tips for Cancelling Multiple Subscriptions

I am working with an array of subscribeToMore from Apollo query and I'm looking to implement it in a slightly different way. After reading this article, I got the idea to use a functional component for my project: useEffect(() => { const unsub ...

What could be causing this JSON variable to be undefined?

Check out the code snippet below. JavaScript <script> function saveUserInfo() { var userInfo = $('span input').serialize; alert(userInfo.username); } </script> HTML <span> User name : <input type="text" name="us ...

Enhancing traditional functions with Javascript annotations or decorators

Currently, I am in the process of developing a Next.js application, where I have defined an API as shown below: export default function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method === 'GET') { fn1Get(req, res); } e ...

Tips on removing previously selected files from a Bootstrap 4 input file

I am currently facing an issue with a form that includes an input file implemented using Bootstrap 4. The functionality of this input file depends on Javascript: when the user clicks on the "browse files" button, a window opens for file selection, and upon ...