Fun with Functions : The JavaScript Way – Part 2

Now let’s start from where we left. Let us understand few more concepts in functions.

4. Passing variable number of arguments to a function

In JavaScript, and in few other languages it is possible to send multiple number of arguments to the same function. Usually in general if our functions accepts two arguments, then while calling the function, we pass only two parameters. But in this case we can pass any number of parameters to the function. See the below code snippet.

//Passing multiple arguments to the function
const multipleArgumentNomal = function() {
    let sum = 0;
    let i;
    for(i =0; i < arguments.length; i++){
        sum += arguments[i];
    }
    return sum;
}

const multipleArgumentArrow = (...arguments) => {
    let sum = 0;
    let i;
    for(i =0; i < arguments.length; i++){
        sum += arguments[i];
    }
    return sum;
}
result = multipleArgumentNomal(5,6,7);
console.log(result);

result = multipleArgumentArrow(5,6,7,4);
console.log(result);

Here we have two functions, one in the normal way and the other using the arrow syntax. In the normal method we have a property called arguments, which stores all the parameters that is passed to the function. This arguments variable is implicitly provided by the JavaScript engine and we don’t have to add this in our function definition parameters list. The arguments is a list and can be used in similar fashion. In our example we are using a loop to iterate over the arguments list and finding there sum. In the case of arrow syntax however we have to pass …arguments to the function so that we can use it similar to the normal function.

5. Returning multiple values from a Function

In JavaScript we can return multiple values from a function. We use { and } to wrap our return variables and use the same variable names with let and { and } to receive the return values from a function call. This is a handy little use case that sometimes can save us from writing redundant code. See the code snippet below

//Returning multiple values from the function
const calculator = function(num1, num2) {
    let sum = num1 + num2;
    let diff = num1 - num2;
    let product = num1 * num2;
    let quotient = num1 / num2;

    return {sum, diff, product, quotient};
}

let {sum, diff, product, quotient} = calculator(20, 5);
console.log(sum);
console.log(diff);
console.log(product);
console.log(quotient);

6. Passing function as Arguments

This concept is called callback. Here you pass one function as an argument to another function. Usually the argument function will be called when the main function is done with execution. This is mostly used in asynchronous patterns where we want to execute some code once the asynchronous operation is done.

In the below example, we have created two functions. findAverage and displayAlert. findAverage takes a list of integers and finds the average and takes a function called callback and executes it at the end of the function definition. displayAlert function takes an argument and displays it in an alert prompt. This displayAlert is passed to the findAverage function as a callback and is called when the function execution has happened along with the required parameters. See the code snipped below.

const findAverage= function(list, callback) {
    let sum = 0;
    for(let i = 0; i < list.length; i++){
        sum += list[i];
    }
    let average = sum / list.length;
    callback(average);
}

const displayAlert = function(value){
    alert(value);
}

let list = [20, 30, 40, 50, 80];
findAverage(list, displayAlert);
findAverage(list, average => console.log(average));

In the first call we are passing the name of the function called sisplayAlert which is defined previously. In case of second function call we are passing the function inline which does a console log. This inline function is treated as call back function as well.

7. Returning a function from another function

Just FYI: This is where the concept of closure begins

Now since we know that we can pass a function as an argument, can we return a function as a function’s return type? The answer is obviously yes. We can. See the below code snippet.

const Adder = (num1) => {
    function innerAdder(num2){
        return num1 + num2
    }
    return innerAdder;
}

Here we have a function called as Adder. It takes one argument. Inside the function there is a definition of another function called innerAddedr which takes another argument and adds both the arguments i.e., num1 and num2. Then the innerAdder function is returned. Now let us call the function like below

const Add10 = Adder(10);
result = Add10(3);
console.log(result); //13

Now if you see, we have created a constant called as Add10 which calls Adder with argument 10. Adder return the function to Add10 and Add10 is now a function. Here Add10 already has the argument num1 as 10. Now this will add 10 and the argument that we pass to it. In our example we are calling Add10 with parameter. Now Add10 will return 10 + 3 which is 13 to result. See another example below

const Add20 = Adder(20);
result = Add20(4);
console.log(result); //24

Here we are calling Adder with 20. So now it will add 20 and another number. Add20 is the function now. We call Add20 with argument 4. This will add 20 + 4 which is 24 and will return as result.

I understand this is little tricky initially. But once you wrap your head around, this is really easy, handy and useful thing to do. Specially when you write your own frameworks and libraries.

We have already covered quite a number of concepts in functions already. But there is more. It is really a vast topic. I will write more about functions in part 3 of this series. So stay tuned !.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: