0

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?

Roman
  • 4,922
  • 3
  • 22
  • 31
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155
  • So you understand the syntax of the arrow functions? And you could produce the code for `test` with `function`? – Bergi Feb 14 '18 at 19:56
  • yes, they are declaring other functions – Willem van der Veen Feb 14 '18 at 19:56
  • What in particular is vague? Would it help to introduce a temporary variable for the `test('foo')` part of the expression? – Bergi Feb 14 '18 at 19:58
  • 1
    `test` references an arrow function that when called returns another arrow function. `'foo'` is being passed in as an argument to `test` which only has one parameter named `fn` and that is probably not the best name for a variable holding a string and could be contributing to your confusion. – Paul Feb 14 '18 at 19:59
  • 1
    Did you have a look at [What do multiple arrow functions mean in javascript?](https://stackoverflow.com/q/32782922/1048572) – Bergi Feb 14 '18 at 19:59
  • Got it now after rewriting, sorry kind of bad question – Willem van der Veen Feb 14 '18 at 20:00

3 Answers3

2

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.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
2

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'))
Roman
  • 4,922
  • 3
  • 22
  • 31
1

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"

Tim Han
  • 166
  • 1
  • 12