Today I observed the following syntax (simplified example):
const test = fn => () => console.log(fn)
test('foo')();
Having a hard time wrapping my head around this but it still remains vague to me. What exactly happens step by step?
Today I observed the following syntax (simplified example):
const test = fn => () => console.log(fn)
test('foo')();
Having a hard time wrapping my head around this but it still remains vague to me. What exactly happens step by step?
Let's rewrite this in a way which maybe more understandable for you
const test = function(fn){
return function (){
console.log(fn);
}
}
test('foo')();
Do you understand it now? If yes this is same as your example just uses normal function instead of arrow functions.
You also need to know what a closure is to understand this.
As the answers already mentioned you are creating a closure.
In my answer, I want to say what it is a closure good for:
Imagin you want to greet three persons and two of them are your frinds and one is your boss. You want to greet your frinds with "Hi" but your boss with "Hello".
const greet = greetingWord => name =>
`${greetingWord}, ${name}`
const greetFrind = greet('Hi')
const greetBoss = greet('Hello')
We create a function greet
which takes one arguement an will return a new function with one argument too (greet = greetingWord => name
). Once we implement it we can define a greeter for our frinds and for the boss.
const greet = greetingWord => name =>
`${greetingWord}, ${name}`
const greetFrind = greet('Hi')
const greetBoss = greet('Hello')
console.log(greetFrind('Paul'))
console.log(greetFrind('Julia'))
console.log(greetBoss('Mr. Paker'))
So this is basic concept of closure in JavaScript. If you rewrite the code in ES5:
var test = function(fn){
return function(){
console.log(fn);
};
}
test('foo')();
So the inner function has access to the argument that was passed into the outer function. So that's why you are getting "foo"