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

1

6

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?

Bagatelle answered 14/6, 2020 at 0:55 Comment(2)
It is IIFE, and it looks like compiled code. Before modifying, check that it isn't generated/compiled code, because if it is, the source will be a lot easier to read. If that's the source, then the value in the brackets is the value to invoke the function with.Premier
I was not initially aware that it was generated/compiled code. I then checked and found that it was. I found the source and it is indeed easier to read. It was exactly what mrlew in another answer mentioned below _getURLJWT(message). Thanks for your comment.Bagatelle
B
4

_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.
Balikpapan answered 14/6, 2020 at 1:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.