0

How to use a mathematical symbol as a variable for a mathematical operation in Javascript?

Works:

if(1 < 2) alert("yes");

Fails:

var sign = "<";
if(1 sign 2) alert("yes");

1 Answers1

2

You can use eval:

if(eval('1' + sign + '2')) alert("yes");

But eval is frowned upon for many good reasons, so as an alternative, you could check the sign and perform the relevant test. For example:

if(test(1, 2, sign)) alert("yes");

function test(x, y, sign){
  switch (sign) {
    case "<":
      return x < y;
    case ">":
      return x > y;
    case "==":
      return x == y;
    // Add a case for each sign you wish to support
  }
  return false;
}
Paul
  • 139,544
  • 27
  • 275
  • 264