0

Having two functions one wrapping the other, how to pass a parameter down correctly? At the moment the console logging does not work.

const a = (v) => (v) => console.log(v);
a(2);
Omri Attiya
  • 3,917
  • 3
  • 19
  • 35
vuvu
  • 4,886
  • 12
  • 50
  • 73
  • https://stackoverflow.com/questions/32782922/what-do-multiple-arrow-functions-mean-in-javascript – Roope Aug 27 '19 at 12:12
  • 1
    it doesn't work because you have 1 more `(v) =>`. Make it like this - `const a = (v) => console.log(v);` and it will work – Bakudan Aug 27 '19 at 12:14
  • 1
    `a(2)` will execute the *first* function and return *another* function - `(v) =>console.log(v);`. So you need to execute the result again. Note that the two `v` parameters shadow themselves, so you need `a(1)(2)` but it's irrelevant what `1` actually is or if it's passed in. – VLAZ Aug 27 '19 at 12:15
  • It's not clear whether or not you know that you need to invoke this with `a()(2)`, or if you're trying to do `(v) => () => console.log(v)` so that you can say `hi = a('hello'); hi(); hi(); hi();` and get `hello hello hello` – Wyck Aug 27 '19 at 13:54

4 Answers4

2

Passing a parameter in High order fn is easy as the value get set to closure

const a = v => () => {console.log(v)};
a(2)()

No matter how deep you go, parameter passed to fn get set to closure space when a fn having a parameter v either returns a fn or executes a fn which uses that parameter v

const a = v => () => () => () => {console.log(v)}
a(2)()()()
Satyam Pathak
  • 6,612
  • 3
  • 25
  • 52
1

If you really want to work on two functions

const a = (v) => (a = v) => console.log(a);

a(2)()
Abdulsamet Kurt
  • 1,090
  • 2
  • 10
  • 15
1

What you did over there to define a lambda function within a function. If you want it to work with a(2) you need to excecture the inner function (meaning to add () at the end), like this:

const a = (v) => (() => console.log(v))();
a(2);

This (() => console.log(v)) is a function, when you add () at the end it's actually activating that function, and that's why what you did, didn't work.

Omri Attiya
  • 3,917
  • 3
  • 19
  • 35
0

You have two v variables, and the inner one is shadowing the outer one since they have the same name. Unless you rename the inner v, there's no way to access the outer v from inside that function.

Matthias
  • 13,607
  • 9
  • 44
  • 60