Are there known problems with >= and <= and the eval function in JS?

Posted by Augier on Stack Overflow See other posts from Stack Overflow or by Augier
Published on 2012-09-21T09:08:28Z Indexed on 2012/09/21 9:37 UTC
Read the original article Hit count: 268

Filed under:
|

I am currently writing a JS rules engine which at one point needs to evaluate boolean expressions using the eval() function.

Firstly I construct an equation as such:

var equation = "relation.relatedTrigger.previousValue" + " " + relation.operator +
        " " + "relation.value";

relation.relatedTrigger.previousValue is the value I want to compare.

relation.operator is the operator (either "==", "!=", <=, "<", ">", >=").

relation.value is the value I want to compare with.

I then simply pass this string to the eval function and it returns true or false as such:

return eval(equation);

This works absolutely fine (with words and numbers) or all of the operators except for >= and <=. E.g. When evaluating the equation:

relation.relatedTrigger.previousValue <= 100

It returns true when previousValue = 0,1,10,100 & all negative numbers but false for everything in between.

I would greatly appreciate the help of anyone to either answer my question or to help me find an alternative solution.

Regards,

Augier.

P.S. I don't need a speech on the insecurities of the eval() function. Any value given to relation.relatedTrigger.previousValue is predefined.

edit: Here is the full function:

function evaluateRelation(relation)
{
console.log("Evaluating relation")
var currentValue;

//if multiple values
if(relation.value.indexOf(";") != -1)
{
    var values = relation.value.split(";");
    for (x in values)
    {

        var equation = "relation.relatedTrigger.previousValue" + " " + relation.operator +
        " " + "values[x]";
        currentValue = eval(equation);
        if (currentValue)
            return true;
    }
    return false;
}

//if single value
else
{
    //Evaluate the relation and get boolean
    var equation = "relation.relatedTrigger.previousValue" + " " + relation.operator +
        " " + "relation.value";
        console.log("relation.relatedTrigger.previousValue " + relation.relatedTrigger.previousValue);
    console.log(equation);
    return eval(equation);
}
}

Answer: Provided by KennyTM below. A string comparison doesn't work. Converting to a numerical was needed.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about eval