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
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
(identifier:string) => myFunction(identifier)
is a function accepting identifier
of type string and returning the result of application myFunction
to it.fun('Hi')
is a call of the function fun
with 'Hi'
argument.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
((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.