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

Setting nodeIntegration to false led to an Uncaught ReferenceError: require is not defined when trying to access Object.url (external "url":1) in the electron-react-typescript environment

After setting nodeIntegration to false, I encountered the following error message: "Uncaught ReferenceError: require is not defined at Object.url (external 'url': 1)". https://i.sstatic.net/galzh.png Upon clicking on the link referring to "exte ...

Is your Bootstrap input displaying the has-error class with a glyphicon, but the alignment is not vertically centered?

What is the reason for the misalignment of glyphicon-warning-sign form-control-feedback vertically in the code below after applying font-size: 20px; to the label? <div class="container"> <div class="content align-left contact"> ...

Replace all instances of the same word with the word "and" using regular expressions

If we look at the sentence below: Blue shirt blue hat Can regular expressions be used to detect 2 matching words and replace the second one with and so it reads: Blue shirt and hat Now, let's tackle a more complex example. In this case, we nee ...

"Enhance Your Sublime 3 Experience with a Jade Syntax Highlighter, Linting, Auto Complete, and

After trying out the recommended packages for Sublime Text, I'm still not satisfied with how they handle syntax highlighting, code linting, and auto suggestion. Could anyone recommend a comprehensive package specifically for Jade? ...

Combining the power of ExpressJS with a dynamic blend of ejs and React for an

My current setup involves a NodeJS application with an Express backend and EJS for the frontend. The code snippet below shows an example route: router.get("/:name&:term", function(req, res) { Course.find({ courseName: req.params.name, courseTerm: req.p ...

Fixing Laravel 5.2 and jQuery validation issue: Accessing a property from a Non-Object

Currently, I am utilizing the jQuery validation plugin to check whether a username already exists or not. The documentation regarding the validation plugin states: The server-side resource is accessed through jQuery.ajax (XMLHttpRequest) and receives k ...

The property 'createDocumentFragment' is not defined and cannot be read in JavaScript code

I'm working on loading data from my database using ajax, but I'm facing an issue with the this method not functioning as expected. Below is a snippet of my source code: $(".cancel-btn").click(function() { var cancelArea = $('.cancel&apos ...

Is there a way to create a div that resembles a box similar to the one shown in the

Hello, I am attempting to achieve a specific effect on my webpage. When the page loads, I would like a popup to appear at the center of the screen. To accomplish this, I have created a div element and initially set its display property to 'none'. ...

Experiencing slow loading times with a Next.js app in the development environment

Currently, I am in the process of building a Next.js application and I have noticed that it takes quite a long time to load in the development environment. At the start, the page becomes unresponsive and if I cancel the request, it stops loading altogeth ...

What is the best way to extract data from the ajax.done() function?

My question revolves around the function shown below: $.ajax({ url: "../../getposts.php" }).done(function(posts) { var postsjson = $.parseJSON(posts); }); I am wondering how I can access the variable postsjson outside of the .done() function sco ...

The process of generating collection names dynamically based on user information

My goal is to enhance the structure of my data collection and make it more organized. While I am familiar with accessing and retrieving data, I am unsure about creating the schema. Here is my current schema: var MySchema = new Schema ({ event: { ...

Issues with expanding all nodes in the Angular Treeview function by Nick Perkins in London are causing difficulties

Currently utilizing the angular treeview project found here: https://github.com/nickperkinslondon/angular-bootstrap-nav-tree After examining the functionality, it seems that this treeview is lacking search capabilities. To address this limitation, I deci ...

The build process encountered an error while processing the module vue-router.esm.js in a Vue.js

Just started using VueJs and decided to incorporate the cli-plugin-unit-jest into my project. However, after adding it, I encountered the following error: Failed to compile. ./node_modules/vue-router/dist/vue-router.esm.js Module build failed: Error: ENO ...

Utilize JavaScript to trigger a div pop-up directly beneath the input field

Here is the input box code: <input type='text' size='2' name='action_qty' onmouseup='showHideChangePopUp()'> Along with the pop-up div code: <div id='div_change_qty' name='div_change_qty&ap ...

Why isn't this working? I'm attempting to trigger a sound when I hover with my cursor, but it only plays when I click instead

When I click on it, it works fine. But I can't seem to get it to work on hover. Can someone help me out? This is the HTML code: <body> <audio autoplay id="HAT2" > <source src="OOOOO_1_HAT.mp3" > Your browser doesn't support t ...

I'm looking to develop a custom CKEditor plug-in that will allow users to easily drag and drop elements within the editor interface

Upon observing that dragging and dropping text or images within a CKEditor editor instance does not trigger the "change" event, I devised a temporary solution by implementing code triggered by the "dragend" event. However, my ultimate goal is to create a C ...

How can I use jQuery to add styling to my menu options?

Looking to customize my menu items: <ul> <li class="static"> <a class="static menu-item" href="/mySites/AboutUs">About Us</a> </li> <li class="static"> <a class="static-menu-item" href="/m ...

Apigee Usergrid: Absence of bulk delete feature

Currently, I am utilizing usergrid for storage in a customer project. The data is divided into two collections: carShowrooms and cars. Thus far, everything has been running smoothly. However, there arises a situation where I need to refresh the masterdata ...

Replacing JS/CSS include sections, the distinction between Debug and Release versions

Can you share how you manage conditional markup in your masterpages for release and debug builds? I am currently using the .Net version of YUI compress to combine multiple css and js files into a single site.css and site.js. One idea I had was to use a u ...

Understanding Vue.js: Effectively communicating updates between parent and child components using scoped slots

My goal is to develop a component with two slots, where the second slot repeats based on the number of items in the first slot. I have successfully implemented this using scoped slots. However, I noticed that when the data in the first slot is updated, the ...