5

In PHP I can do:

// $post = 10; $logic = >; $value = 100
$valid = eval("return ($post $logic $value) ? true : false;");

So the statement above would return false.

Can I do something similar in JavaScript? Thanks!

Darren.

2
  • 1
    Why would you want to do this? Commented Jan 11, 2010 at 13:10
  • 1
    Also, $post $logic $value returns a boolean, so there's no need for ? true : false... Commented Jan 11, 2010 at 13:11

4 Answers 4

35

If you want to avoid eval, and since there are only 8 comparison operators in JavaScript, is fairly simple to write a small function, without using eval at all:

function compare(post, operator, value) {
  switch (operator) {
    case '>':   return post > value;
    case '<':   return post < value;
    case '>=':  return post >= value;
    case '<=':  return post <= value;
    case '==':  return post == value;
    case '!=':  return post != value;
    case '===': return post === value;
    case '!==': return post !== value;
  }
}
//...
compare(5, '<', 10); // true
compare(100, '>', 10); // true
compare('foo', '!=', 'bar'); // true
compare('5', '===', 5); // false
Sign up to request clarification or add additional context in comments.

2 Comments

I love the endlessness of possibilities with coding. Cool shortener.
lot of people here suggesting using eval. please for the love of GOD do not use eval. xD avoid it like the plague. this is probably the best answer here
11

yes, there's eval in javascript as well. for most uses it's not considered very good practice to use it, but i can't imagine it is in php either.

var post = 10, logic = '>', value = 100;
var valid = eval(post + logic + value);

1 Comment

Note: It's not safe.
2

A little late, but you could've done the following:

var dynamicCompare = function(a, b, compare){
    //do lots of common stuff

    if (compare(a, b)){
        //do your thing
    } else {
        //do your other thing
    }
}

dynamicCompare(a, b, function(input1, input2){ return input1 < input2;}));
dynamicCompare(a, b, function(input1, input2){ return input1 > input2;}));
dynamicCompare(a, b, function(input1, input2){ return input1 === input2;}));

Comments

1

JavaScript have an eval function too: http://www.w3schools.com/jsref/jsref_eval.asp

eval("valid = ("+post+logic+value+");");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.