Saem
Saem

Reputation: 197

Naming function call after variable assignment

I have unusual problem.

I don't know how to put into words given operations in JavaScript example.

var FunctionLayer2 = FunctionLayer1(2);  //How to put into words this variable assignment and calling FunctionLayer1()

FunctionLayer2(4); //How to put into words calling function from the created variable with output based on the argument from previous call

function FunctionLayer1 (value1) {

    console.log(value1);

    return (function (value2) {
        console.log(value2*value1);
    })
}

Sorry for this unusual question but i have found about this functionality recently and couldn't find much about it before.

Upvotes: 1

Views: 34

Answers (1)

The Reason
The Reason

Reputation: 7983

The patter you are trying to use is called currying. This is when you return a function from another function.

function sample(str){
  return function(anotherStr){
    return str + '' + anotherStr
  }
}

var foo = sample('Hello')
var result = foo('StackOverflow')
console.log(result) // 'Hello StackOverflow'

your case:

function multiply(x){
  return function(y){
    return x * y
  }
}

var multiply3 = multiply(3)
var multiply3By4 = multiply3(4)
console.log(multiply3By4) // 12

Here is a blog with a simple examples & description about currying so it might be useful for you

Upvotes: 1

Related Questions