0

I would like to understand what this expression means and when it's useful

((identifier:string) => myFunction(identifier))('Hi')

myFunction

const myFunction = (str:string) => { console.log(str) }

Console output:

Hi
Michael Nelles
  • 5,426
  • 8
  • 41
  • 57
  • 2
    Some context, please? Where did you see this function? – JLRishe Jan 27 '20 at 16:26
  • 1
    Does this answer your question? [What is the (function() { } )() construct in JavaScript?](https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) – ASDFGerte Jan 27 '20 at 16:27
  • The first example is an 'IIFE', "Immediately Invoked Function Expression", with an arrow function. – byxor Jan 27 '20 at 16:27

2 Answers2

0
  1. (identifier:string) => myFunction(identifier) is a function accepting identifier of type string and returning the result of application myFunction to it.
  2. fun('Hi') is a call of the function fun with 'Hi' argument.
  3. fun from 2. is declared in-place in the example 1.

That said, it’s the same as

const myFunction = (str:string) => { console.log(str) }
const myFunction2 = (identifier:string) => myFunction(identifier)
myFunction2('Hi') //⇒ Hi
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
0

((identifier:string) => myFunction(identifier))('Hi')

Here you have a self calling anonymous function, which accepts 1 parameter identifier, which is passed at the end. Hi in this case. So a self calling anonymous function syntax is something like this: (() => {})() where external () just wrap anonymous function. () => {} is anonymous arrow function and () at the end calls that function where you can pass parameters.

It can be useful when you have some top level function that has to run when script is loaded and evaluated. Of course same can be achieved with a named function. Plus if you do this without caution then you might slow down initial page loading I believe. Otherwise you can put this kind of code anywhere, but I don't recommend doing so, because it affects readability. So either assign anonymous function to a variable or created a named function and call that.

Blind Despair
  • 3,190
  • 2
  • 20
  • 31