Wednesday 6 December 2017

JavaScript | mul function to multiply three variables in JavaScript

Write a mul function which will produce the following outputs when invoked:
console.log(mul(2)(3)(4));
Output : 24

console.log(mul(4)(3)(4));
Output : 48

Function is,
function mul (x) {
    return function (y) { // anonymous function
        return function (z) { // anonymous function
            return * y * z;
        };
    };
}

Output:
mul(2)(3)(4)
24

Here the mul function accepts the first argument and returns an anonymous function, which takes the second parameter and returns another anonymous function that, will take the third parameter and return the multiplication of the arguments that have been passed.

mul(2)(3)

Output:
ƒ (z) { // anonymous function
       return x * y * z;
 }

In JavaScript, a function defined inside another one has access to the outer function's variables. Therefore, a function is a first-class object that can be returned by other functions as well and be passed as an argument in another function.

A function is an instance of the Object type.
A function can have properties and has a link back to its constructor method.
A function can be stored as a variable.
A function can be passed as a parameter to another function.

A function can be returned from another function.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...