Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does var name = ()() do? [duplicate]

I encountered the code like below.

return new Promise(function (resolve, reject) {
      if (!message) return reject(new Error('Requires message request to send'));
      message = (0, _getURLJWT)(message);
      .....
      .....
      var enc = (0, _encryptMessage)(plaintext, pubEncKey);

      }, function (error, res, body) {
       ....
       ....
      });
    });

I do not understand the two expressions in the code:

message = (0, _getURLJWT)(message);
var enc = (0, _encryptMessage)(plaintext, pubEncKey);

This looks like IIFE(Immediately invoked function expression), however, I do not understand how the brackets at the end of the line exactly work or what they are doing.

Could anyone help me understand this?

like image 480
Gem Cutter Avatar asked Jun 14 '20 00:06

Gem Cutter


People also ask

Can you have duplicate variable names in a project?

It is legal for 2 variables in different scope to have same name. Please DO read §6.3. Scope of a Declaration from JLS. Below are few of the statement from that section.

Can you have duplicate variable names in a project C#?

Essentially, it's not allowed because, in C#, their scopes actually do overlap.

Can var be used as a variable name?

Variable Names in JavaScript A variable name cannot start with a digit 0-9. A variable name cannot be a reserved keyword in JavaScript, e.g. var, function, return cannot be variable names.

Can a variable name be changed?

The variable's name represents what information the variable contains. They are called variables because the represented information can change but the operations on the variable remain the same.


Video Answer


1 Answers

_getURLJWT and _encryptMessage are probably functions that are called with the arguments message and plaintext, pubEncKey, respectively.

When you write two values separeted by comma operator, Javascript evaluate all of its operands and returns the last one. So 0, 1 will evaluate 1.

So, (0, _getURLJWT)(message) will evaluate to _getURLJWT(message)

For instance:

console.log((0,1)); //1

(0, (myArg) => console.log(myArg))('hello'); //hello

Reason to use this technique

Calling this way ensures that the function is called with this set to the global object.

const myObj = {
    printMe: function() { console.log(this); },
}

myObj.printMe(); //{printMe: ƒ}

(0, myObj.printMe)(); // Window {parent: Window, opener: null...} <= loses reference, the this will not longer be bound to myObj, but will be bound to the global object.
like image 75
mrlew Avatar answered Oct 24 '22 04:10

mrlew