What does var name = ()() do?

Viewed 87

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?

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.
Related