Translate String to operation in javascript

Is there a way to translate something like the following logical operation (which uses a string due to user input)? Or will I have to check for every possibility? (> < => == =< etc.)

var x = 5;
var y = 3;
var operator = '>'

if (x operator y)


if (x > y)


You could use eval, providing you know that it is evil. Though you should definitely check if the input is valid, for example checking if it only contains the '><=' characters.

Yes, with an object and appropriate functions, like

var comparer = {
    '>': function (a, b) { return a > b; }


if (comparer[operator](x, y)) {

You should change your way. With eval you must whitelist all operators and sanitize both inputs.

Build your own interface for your needs. May be it will switch:

switch (operator) {
  case '>': if (x > y) doSomething();

May be some more abstracted like:


May be even you'll write your own small interpreter(parser/lexer) and your users will can to write program on it.

It will be used in an web application where users can create there own small (simple) applications for the use of data. – Mathieu Brouwers

What you should not to use here is eval.

Need Your Help

How to get all changes to a file in Git, with Lib2GitSharp

c# .net git libgit2sharp

I want to be able to Get a list of all changes done to a file. I've seen this post

XCode 3.1.2, header file not found

xcode file header

I have been trying to build a code that has dependencies with other header files that are not in the project directory. I added the paths to these header files in both HEADER_PATH and USER_PATH. Ho...