lluiscab lluiscab - 1 month ago 8
Javascript Question

Javascript: If variable mets a condittion defined on another variable

My problem is simple but I can't find a way to make thag work

The idea is that if a variable (number) mets a condittion defined on another variable (cond), run some code

Example:

var cond = '> 4';
var number = 5;
// Some type of if statement to check if 5 is > 4

Answer

You can use eval but usually if you resort to eval, you're not understanding the problem correctly.

var cond = '> 4';
var number = 5;
if (eval(number + cond)) {
  console.log(number + cond);
}

Another possibility would be to create functions which correlate with the condition then store the operand in another variable.

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

var op = '>';
var operand = 4;
var number = 5;
if (compareFunctions[op](number, operand)) {
  console.log(number + op + operand);
}