Is it possible to create custom operators in JavaScript?

javascript operator overloading
typescript custom operators
javascript new
javascript new function
javascript create instance of function
js new
javascript macro
const new 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?

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.

Define your custom JavaScript operators, Contribute to IonicaBizau/js-custom-operators development by creating an code from the syntax tree esprima spits - we can create new JavaScript operators​. The above statement evaluates to z being assigned the value 44. As you can see, precedence can greatly influence the final value of a calculation. If operator precedence isn't taken into consideration, you can have bugs in your calculations unknowingly. The order of precedence for basic JavaScript operators are as follows: 1. Grouping or parenthesis. 2.

No. JavaScript does not support operator overloading . but you can make a class method for doing this

var mathClass = function(value){
   this.value = value;
}

mathClass.prototype.toLaw = function(){
   return 2 * this.value;
}

var y = new mathClass(2)
2 + y.toLaw(); //2 + 2 * y

IonicaBizau/js-custom-operators: Create your own , The closest thing you can achieve in JavaScript is fake operator Perform the function call def("Ninja") which creates a new constructor Ninja  Custom operators in JavaScript? This projects finally bring this feature in the JavaScript world! :-) Using esprima - which takes JS code and generates the syntax tree for it - and escodegen - which does the other direction, generating JS code from the syntax tree esprima spits - we can create new JavaScript operators.

You can add pseudo-operators via methods on Number.prototype:

Object.defineProperty(Number.prototype, 'myOp', {
    value: function(that) {
        return this + 2 * that;
    }
});

Then all of this syntax will work

alert( (2).myOp(2) )
alert( 2 .myOp(2) )
alert( 2..myOp(2) )
alert( 2.0.myOp(2) )

2.myOp(2) does not work because the period is treated as a decimal point

Fake operator overloading in JavaScript, Creating a user-defined object requires two steps: Define the object type by writing a function. Create an instance of the object with new . To  So yes, it is possible to create operators using C#, although you must keep in mind that there are some technical challenges since the SMSDK itself and its interfaces are all native C++. I have indirectly responded to your interest in using GeoMedia objects, as well.

No. You can't do that in JS.

The closest you can have IMO is to implement your own object which has a chainable interface, aka "fluent" syntax. That way you can operate as if you were speaking out in sequence.

var eq = new YourEquationObject();

// Then operate like 1 - 2 * 3
eq.add(1).sub(2).mul(3);

Details are up to you though. Just giving out an idea.

new operator, This chapter describes JavaScript's expressions and operators, You can use the new operator to create an instance of a user-defined object  The most common iterator in Javascript is the Array iterator, which simply returns each value in the associated array in sequence. While it is easy to imagine that all iterators could be expressed as arrays, this is not true. Arrays must be allocated in their entirety, but iterators are consumed only as necessary and thus can express sequences

The slightly longer then the short one is that Yes you can, but its a bit more involved then what you did in Math class

To extend the language with new constructs you can use a transformer like http://esprima.org/ or any of the others. You need to define your syntax, write the parser to parse your statement and finally add the actual code to do the math parts. When these parts is in place you have made a new language that works just as javascript but with the added support of the operator.

Its really not that hard to add new syntax, here is facebooks example how they add => arrow function syntax

https://github.com/facebook/jstransform/blob/master/visitors/es6-arrow-function-visitors.js

Expressions and operators, Note: the only overloadable operator in the following is + because that's the only We can intercept the toString method by creating a proxy object which wraps JS developers tend to throw random stuff into their module to make it custom. The assignment operator ( =) assigns a value to a variable. The multiplication operator ( *) multiplies numbers. Arithmetic operators are fully described in the JS Arithmetic chapter. Assignment operators assign values to JavaScript variables. The addition assignment operator ( +=) adds a value to a variable.

JavaScript Operator Overloading - Julian Knodt, The library comes with many operators, which can be used to deal with almost every situation Creating Custom Operators in RxJS Akita: State Management Tailored-Made for JS Applications; Spectator: A Powerful Tool to  At least if I'm reading things correctly, it's (internally) translating your custom operator into an overload of an existing operator. That makes things easier, at the expense of some flexibility -- for example, when you create a new operator in ML, you can give it precedence different from that of any built-in operator.

Creating Custom Operators in RxJS, The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program. The examples below make use of the log function of the console object and that almost all Web browsers provide the alert function, alert can also be The new operator can be used to create an object wrapper for a Boolean  The direction of the shift operation is controlled by the operator used. Shift operators convert their operands to 32-bit integers in big-endian order and return a result of the same type as the left operand. Only the low five bits of the right operand will be used.

JavaScript syntax, Although the factory pattern can create multiple similar objects, it doesn't allow you to JavaScript allows you to create a custom constructor function that defines the properties To create a new instance of Animal , you use the new operator. Recognizing an operator as an operator is a separate process from deciding what the operator actually does, and is much more tightly integrated into the compiler - which is why you can customize the latter but not the former.

Comments
  • Another name for this is infix function notation - the answer is no, you cannot
  • You could try to exploit valueOf with existing operators, but that's about it in JavaScript.
  • I would argue that it's a really bad idea to want to define an operator for which the symbol does not feature on my keyboard
  • No. You can't do that in JavaScript. However, you can do it in Haskell. First line: infixl 6 ∘. Second line: x ∘ y = x + 2 * y.
  • Technically you can, by writing your own lexical parser and defining your own name of script type in the <script> block. This technique is used quite widely. Some well-known examples include Google Traceur.
  • Can you add a reference? How will I define such an operator after it will be implemented?
  • I doubt any version of ECMAScript comes with the ability to define new symbolic operators - that's normally reserved for languages like haskell. I suspect it'll only come with operator overloading
  • @Eric what Haskell does is not magic. There is no trouble introducing backticks for infix notation in JS :) However yes, the current proposal discusses operator overloading.
  • @BenjaminGruenbaum: Sure, it's not magic, but defining symbolic operators is a slippery slope to perl
  • I see no mention on the ECMAScript page on value objects suggesting that user code can declare new value types