Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic if statement in Javascript

Tags:

javascript

Is there anyway to convert a string to a condition inside if statement:

example:

var condition = "a == b && ( a > 5 || b > 5)";

if(condition) {
    alert("succes");
}
like image 412
Ayoub k Avatar asked Mar 18 '19 15:03

Ayoub k


2 Answers

A safer alternative to eval() may be Function().

var condition = "4 == 4 && ( 10 > 5 || 9 > 5)";
var evaluate = (c) => Function(`return ${c}`)();

if(evaluate(condition)) {
    alert("succes");
}

Per MDN:

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, a third-party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.

like image 86
Tyler Roper Avatar answered Oct 22 '22 19:10

Tyler Roper


You can use new function

let a = 6;
let b = 6
var condition = "a == b && ( a > 5 || b > 5)";

let func = new Function('a','b', `return (${condition})` )

if(func(a,b)) {
    alert("succes");
}
like image 21
Code Maniac Avatar answered Oct 22 '22 21:10

Code Maniac