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.

6 comments:

  1. Great Article android based projects

    Java Training in Chennai Project Center in Chennai Java Training in Chennai projects for cse The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

    ReplyDelete
  2. Excellent article..ts a good site to explore ..Thanks for the blog post.Really thank you! Much obliged.. ppc management

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...