2

I'm looking at some javascript code that does this:

const senderPubKey = (0, secp256k1_1.ecdsaRecover)(signature, recovery.toNumber(), msgHash);

I don't understand this syntax. When I do console.log(secp256k1_1.ecdsaRecover) I get [Function: ecdsaRecover] so I'm guessing it's a function call but why not do secp256k1_1.ecdsaRecover(signature, recovery.toNumber(), msgHash)?

neubert
  • 15,947
  • 24
  • 120
  • 212
  • 1
    I know this is a duplicate but it's going to be hard to find. Are you using Typescript? It's something that transpilers use for reasons; that `(0, name)` is a comma expression whose value is a reference to the function to be called. The 0 doesn't mean anything, it's just a simple dummy expression. – Pointy Feb 09 '22 at 15:12
  • 1
    It does indeed look odd or even non-sensical on first glance if you haven't seen it before. The expression `(0, obj.fn)("arg1", "arg2")` is basically `obj.fn.call(undefined, "arg1", "arg2")` or `const fn = obj.fn; fn("arg1", "arg2");`. It avoids setting `this` to `obj` within the call, by using the grouping operator (`()`) around a comma operator expression with the function as the second operand, and then calling the result. The `0` can be any non-side-effecty expression, `0` is handy because it's short. :-) – T.J. Crowder Feb 09 '22 at 15:12
  • Maybe people do it in actual typed-in JavaScript; I don't know. – Pointy Feb 09 '22 at 15:14
  • 1
    @Pointy - Sometimes, yeah. Most common actually-typed-in example I've seen is `(0, eval)("...")` ("indirect eval"), because it disconnects `eval` from local scope, forcing it to eval at global scope. – T.J. Crowder Feb 09 '22 at 15:15
  • But I've used it for callbacks that I stored on an internal object when I didn't want the callback to know about the object. In fact, I was tempted to do it [earlier today](https://stackoverflow.com/a/71045814/157247), but decided to use `.call` instead for clarity. :-D – T.J. Crowder Feb 09 '22 at 15:25

0 Answers0