javascriptoperators

Is it possible to create custom operators in JavaScript?


During the Math classes we learned how to define new operators. For example:

(ℝ, ∘), x ∘ y = x + 2y

This defines law. For any real numbers x and y, x ∘ y is x + 2y.

Example: 2 ∘ 2 = 2 + 4 = 6.


Is possible to define operators like this in JavaScript? I know that a function would do the job:

function foo (x, y) { return x + 2 * y; }

but I would like to have the following syntax:

var y = 2 ∘ 2; // returns 6

instead of this:

var y = foo(2, 2);

Which is the closest solution to this question?


Solution

  • The short answer is no. ECMAScript (the standard JS is based on) does not support operator overloading.

    As an aside, in ECMAScript 7, you'll be able to overload a subset of the standard operators when designing custom value types. Here is a slide deck by language creator and Mozilla CTO Brendan Eich about the subject. This won't allow arbitary operators, however, and the overloaded meaning will only be applied to value types. <- haha that ended up not happening.

    It is possible to use third party tools like sweet.js to add custom operators though that'd require an extra compilation step.

    I've answered with a solution from outside JavaScript using esprima - this is changing JavaScript and extending it, it's not native.