How to change parameter notation?

Hello

Would someone be able to direct me to an article or other which explains how functions can be invoked in different ways?

What I mean by this is say, a function to sum two number that can be invoked by either:

sum(a, b) OR sum(a)(b)

(I realise that the second notation is ambiguous as looks like a product, but I just want to find out how to do this and haven’t been able to find what I’m looking for…)

1 Like

I generally like geeksforgeeks’ explanations.
[ Link: Explain invoking function in JavaScript ]

MDN is awesome too. Just google anything + MDN and you will be enlightened for sure.


Let’s create a function.

const addingUpNumbers = function (a,b) {
       let sum = a + b;
       return sum;
};

This type of function is called a function expression and it’s stored in a variable (const) that I gave the name addingUpNumbers. The name can be anything, doesn’t matter. We will use that name when we’re calling the function.

Then, we have two parameters. Can also be named whatever, but in our case we chose to call them a and b.
Between the curly braces we have the the task that we want the function to do. This code will be executed when we’re calling the function. In our case we want it to add a and b together, and then we want it to return the sum of that.
Sometimes I find it easier to read JavaScript code backwards. Here, we have a + b = sum (in our case, sum is the name of a variable that is holding the value of whatever a + b is).

Now we’ll call it:

addingUpNumbers(10, 40);

The function will take 10 as a and 40 as b, add them up and return the sum. In this case that’ll be 50.

If you want to see the result in the console you can just do this:

console.log(addingUpNumbers(10, 40));

or this:

const result = addingUpNumbers(10, 40);
console.log(result);

I hope that helps a little!

1 Like

This means function should accept differing number of arguments. When there are two arguments passed to it, one thing should happen, when single argument is passed different thing should happen.

sum(a)(b)

This shows that sum(a) returns another function that can be called with single argument. An example written in another way:

const add5 = sum(5);

add5(10);  // 15
add5(0);   // 5

But that would be really an equivalent of:

sum(5)(10);
sum(5)(0);

great, many thanks for the explanations

Excellent. Thanks for all the help

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.