[SOLVED] Pass variables to Function()

Issue

I wish to use the Function javascript feature instead of "eval", for implementing the ability to use comparison operators inside a filtering input field.

function test(){
 let x = 5, y = 10, operator = '>';
 return Function("return x" + operator + "y")(x, y);
}

console.log(test());

The code above throws an error, x, y appear undefined in the Function.

So how can I pass external variables to Function?

Solution

Each parameter referenced in the function body should be a leading argument to the function, in string format.

function test(){
 let x = 5, y = 10;
 return Function('x', 'y', "return x>y")(x, y);
}

console.log(test());

Answered By – CertainPerformance

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *