Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic JavaScript If Statement

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.

like image 709
frontendbeast Avatar asked Nov 27 '22 22:11

frontendbeast


1 Answers

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
like image 62
Christian C. Salvadó Avatar answered Nov 29 '22 13:11

Christian C. Salvadó