I saw a weird function that looked something like:
const x = (a) => (b) => a + b;
console.log(x(1)(2))
The output is 3, I understand that it's a function returning a function and both a and b are in the same scope but the questions I have are:
When one piece of code invokes or calls a function, it is done by the following syntax: variable = function_name ( args, ...); The function name must match exactly the name of the function in the function prototype. The args are a list of values (or variables containing values) that are "passed" into the function.
The syntax for creating a function: let func = new Function ([arg1, arg2, ... argN], functionBody); The function is created with the arguments arg1...
With this closure, you could get a function with a constant value for later adding.
- How could this be used in real life?
You could take the returned function for a mapping of an array.
- What's the advantage of not using a function with 2 parameters and using this instead (for a one-line function)?
It's a cleaner and functional approach.
const
x = a => b => a + b,
add5 = x(5);
console.log([1, 2, 3].map(add5));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With