The syntax in JavaScript of (0, fn)(args) is used to call

I came across an interesting piece of JavaScript code in Google's codebase that I wanted to discuss:

var myVar = function...;
(0, myVar)(args);

Do you know what the significance of this syntax is? I'm struggling to see the difference between (0, myVar)(args); and myVar(args);.

Let me provide a specific example for context

_.x3 = function (a, b) {
    return new _.q3(20 * b.x + a.B.B.x, 20 * b.y + a.B.B.y)
};

And later on

this.ta = new _.s3((0, _.x3)(this.fa, this.B.B), 0);

Answer №1

I had a similar inquiry and eventually uncovered the solution, which goes as follows:

The situation is this

(0, foo.fn)();

It's important to note in JavaScript, when foo.fn() is executed, the context of this within fn is linked to foo. If you attempt

var g = foo.fn;
g();

when g is called above, the reference for this will be tied to the global object (window, in a web browser setting).

Do we need to define g in that manner? Could we do something like

(foo.fn)();

The answer is negative. JavaScript interprets it similarly to foo.fn(); since it is just foo.fn with the redundant () that can be omitted.

However, there is a workaround, involving the use of the comma operator, as described by Mozilla

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand

So by using

(0, foo.fn)();

the expression (0, foo.fn) gets assessed as a reference to the function, akin to g previously, before being executed. Consequently, this isn't connected to foo but rather to the global object.

This approach essentially "cuts the binding".

For instance:

var foo = { 
              fullName: "Peter", 
              sayName:  function() { console.log("My name is", this.fullName); } 
          };

window.fullName = "Shiny";

foo.sayName();       // My name is Peter

(foo.sayName)();     // My name is Peter

(0, foo.sayName)();  // My name is Shiny

Why would one want to cut the binding in certain scenarios? I came across a case where if we have a function:

function foo() {
  // utilizing `this` here
}

Then this would refer to the global object. However, if foo() along with other functions and values are enclosed within a module, upon calling the function using

someModule.foo();

The this would be bound to someModule, altering the behavior of foo(). To maintain the original behavior of foo(), we sever the binding so that within foo(), this remains connected to the global object as before.

Answer №2

The use of the comma operator in this syntax evaluates all operands and returns the value of the last one. In this scenario, 0 acts as a placeholder so that (0, function() {}) will return (function() {}). Once evaluated, the (args) part calls the function and provides its arguments.

Update following a comment:

This coding style is employed for quick execution or to keep code concise on a single line. Consider this example:

var a = 0,
    b = 1,
    c;

c = ( a++, b++, a + 2 ); // Increments a twice and then adds it

a; // 1
b; // 2
c; // 3

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

Sharing an object's attributes as props in Vuejs

Greetings everyone, I am facing some confusion. I am working with two components (child and parent component) where I pass the properties of an object as props <child :child-data="abc" ></child> Vue.componen ...

Displaying a dynamic flag icon in a span element based on the selection from a mat-select

I am working on a mat-select component and I want to dynamically change a flag icon inside a span element in the mat-label based on the selected option. Currently, the initial flag is displayed correctly, but when I click on a different option, the flag d ...

What could be causing the issue with "class not being recognized as a constructor" error that I am encountering?

When attempting to create an instance from modules in routing, I consistently encountered the error message "class is not a constructor." Below is the code snippet: export class Modules{ modules : object = { masterdata : MasterdataModule, shop : ...

Creating objects based on interfaces

After looking at this straightforward code: interface int1 { aa: string, bb: number, } const obj1:int1 = {} //#1 function fun(param_obj:int1) { //#2 } I am curious as to why the compiler throws an error: Type '{}' is missing the fol ...

Retrieve information from a JSON file within a Vue.js application rather than entering data manually

I am venturing into the world of Vue.js for the first time. I have created an app that currently relies on manually added data within the script. Now, I am looking to enhance it by fetching data from a JSON file, but I'm unsure about how to proceed wi ...

Displaying Errors from Controllers in React Hook Forms

Currently, I am attempting to generate required errors for my input element that is enclosed within a Controller component from react-hook-form version 7. The Input consists of a Material-UI TextField structured like this; <Controller ...

What causes the discrepancy in results between the quoted printable encoding operation in JavaScript and Oracle?

Programming Languages: // JavaScript code snippet //https://www.npmjs.com/package/utf8 //https://github.com/mathiasbynens/quoted-printable par_comment_qoted = quotedPrintable.encode(utf8.encode('test ąčęė')); console.log('par_comment_qot ...

Leveraging Polymer web components without the need for a package manager

I am looking to incorporate web components into a static web page without the need for any package manager or JavaScript build process. After referencing , I attempted to import them using unpkg by changing <script type="module" src="node_modules/@pol ...

uib-datepicker-popup allowing for changing minimum mode dynamically

Is there a way to dynamically set the minMode of an Angular Bootstrap Datepicker? I managed to achieve this using the following code: <input type="text" ng-model="myDate" uib-datepicker-popup="{{datepickerFormat}}" datepicker-options="{& ...

Looking to tweak the date format in a Vue.js template?

I received the following format: 2019-01-08T11:11:00.000Z However, I need it to be in this format: 2019-01-08 Does anyone know how to achieve this date formatting without using the moment package? ...

Struggling to get getInitialProps working in dynamic routes with Next.js?

I am encountering an issue. The return value from the getInitialProps function is not being passed to the parent component. However, when I console.log the values inside the getInitialProps function, they appear to be correct. Here is the code snippet: i ...

Issues with clickable links within a table cell

I am facing an issue with a table where rows <tr> are generated dynamically by a PHP loop. I have transformed the entire row into a link, but the problem arises when there is an <input type="checkbox"> within the row. Whenever I check the check ...

Encountering an issue with top-level await in Angular 17 when utilizing pdfjs-dist module

While using the Pdfjs library, I encountered an error message that reads: Top-level await is not available in the configured target environment ("chrome119.0", "edge119.0", "firefox115.0", "ios16.0", "safari16.0" + 7 overrides) /****/ webpack_exports = g ...

Tips for sending textarea data via AJAX with TinyMCE

Recently, I encountered an issue with submitting forms using the TinyMCE Jquery plugin. While regular input fields like text fields and select boxes submit just fine, there seems to be a glitch when it comes to submitting a textarea with TinyMCE. It requir ...

Implementing JavaScript: Grouping JSON Response by Date and Category in a Table

The API response provided below contains sample data. {"success":true,"transaction":[{"_id":"58efd5717ddda769f26793fc","transId":"Exp/04-17/17","trpId":"Trav/dfsd/04-17/12","tripId":"58efd4dc7ddda769f26793f8","userId":"58ac19eaec1e7e4628be6f01","expenseHe ...

There appears to be no data available from the Apollo Query

I'm facing an issue with the returned data from Apollo Query, which is showing as undefined. In my code snippet in Next.js, I have a component called Image with the src value set to launch.ships[0].image. However, when running the code, I encounter a ...

The conditional statement for multiplying in JavaScript

I have a JavaScript function that selects a report number based on multiple parameters (2 checkboxes, 3 dropdown fields), and the current implementation involves a complex conditional statement as shown below: switch(ReportNumDrop) { case 0 ...

Navigating websites: Clicking buttons and analyzing content

When looking to navigate a website's directory by utilizing buttons on the page or calling the associated functions directly, what language or environment is most suitable for this task? After experimenting with Python, Java, Selenium, and JavaScript, ...

Using inertia-links within the storybook framework

Hey there, just wanted to share my experience with storybook - I'm really enjoying it so far! Currently, I'm facing a challenge while implementing it in my Laravel app with Inertia. I'm trying to render a navigation link component that make ...

Having trouble sending an HTTPS request in NodeJS only to receive an HTTP response instead

As I develop my website using NodeJS and deploy it on Heroku, I encountered an issue upon opening the website. Here is the problem at hand: When looking at the main source file of my web application: app.get('/', (req, res) => { var data ...