Using Function() constructor as a closure

I’m trying to do something like this:

function simpleOperations(operation) {
    let myFanction = new Function('a', 'b', 'a ' + operation + ' b');
    return myFanction
}

let sum = simpleOperations("+")
let multiplicate = simpleOperations("*")

console.log("your sum is: " + sum(3,7));
console.log("your product is: " + multiplicate(3,7));

and instead of getting:

your sum is: 10
your product is: 21

I’m getting this:

your sum is: undefined
your product is: undefined

Do you have any thoughts on how to fix it? 🙂

>Solution :

The text body of the function needs to return the value, otherwise your a + b or a * b etc will just be an unused expression.

function simpleOperations(operation) {
    let myFanction = new Function('a', 'b', 'return a ' + operation + ' b');
    return myFanction
}

let sum = simpleOperations("+")
let multiplicate = simpleOperations("*")

console.log("your sum is: " + sum(3,7));
console.log("your product is: " + multiplicate(3,7));

Leave a Reply