How to implement a variable operator in JavaScript?

I am not sure if ‘variable’ is the correct word to use here but essentially, I would like to create a variable operator using JavaScript.

So far, the best thing I can think of is to create a switch statement but it seems very repetitive and tedious to do. Is there any way I can write one "If Statement" with a conditional operator?

What I have thought of:

variableOperator(x, y, operator) {
    switch(operator) {
        case '>=':
            if (x >= y) {
                // logic
            }
            break;
        case '<=':
            if (x <= y) {
                // logic
            }
            break;
        case '<':
            if (x < y) {
                // logic
            }
            break;
        case '<':
            if (x < y) {
                // logic
            }
            break;
    }
}

What I am wondering if is possible in pseudo-code (code below will obviously not work but in concept, this is what ideally I would like to use). No matter what the operator is (greater than, equals to, etc.) this if statement can take care of it:

variableOperator(x, y, operator) {
    if (x operator y) {
        // logic
    }
}

Edit: I should have clarified: x and y don’t always have to be number types.

Mainly, I’m wondering about string (a-z,A-Z,0-9) comparison (== or !=) and number comparison (<, >, <=, >=). The project I’m working on does not need to worry about emoji’s or other complex characters.

In essence, regardless of whether I’m comparing strings or numbers, I’m wondering if the operator itself can be a variable that can be easily manipulated/changed so that one would’t have to write a separate bit of code for each case.

13 thoughts on “How to implement a variable operator in JavaScript?”

Leave a Comment