Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird function syntax

Tags:

javascript

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:

  1. How could this be used in real life?
  2. What's the advantage of not using a function with 2 parameters and using this instead (for a one-line function)?
like image 650
fredtux Avatar asked Jul 02 '19 18:07

fredtux


People also ask

What is the syntax for function?

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.

How do you create a function syntax?

The syntax for creating a function: let func = new Function ([arg1, arg2, ... argN], functionBody); The function is created with the arguments arg1...


1 Answers

With this closure, you could get a function with a constant value for later adding.

  1. How could this be used in real life?

You could take the returned function for a mapping of an array.

  1. 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));
like image 175
Nina Scholz Avatar answered Dec 03 '22 22:12

Nina Scholz