How would you overload the [] operator in javascript

javascript operator overloading es7
typescript operator overloading
babel operator overloading
python operator overloading
java operator overloading
operator overloading npm
javascript operator overloading proxy
javascript override

I can't seem to find the way to overload the [] operator in javascript. Anyone out there know?

I was thinking on the lines of ...

MyClass.operator.lookup(index)
{
     return myArray[index];
}

or am I not looking at the right things.


You can't overload operators in JavaScript.

It was proposed for ECMAScript 4 but rejected.

I don't think you'll see it anytime soon.

Operator Overloading in JavaScript, Operator Overloading. Yep, we're talking about it. Why have operator overloading at all? Useful for new proposed data types - BigInt, Decimal; Operator support  Note: the only overloadable operator in the following is + because that’s the only thing that works on strings. Overloaded operator: Defining or redefining how an operator (+, -, *, /, etc.) acts…


You can do this with ES6 Proxy (available in all modern browsers)

var handler = {
    get: function(target, name) {
        return "Hello, " + name;
    }
};
var proxy = new Proxy({}, handler);

console.log(proxy.world); // output: Hello, world

Check details on MDN.

JavaScript Operator Overloading - Julian Knodt, Note: the only overloadable operator in the following is + because that's the only thing that works on strings. Overloaded operator: Defining or redefining how an  Why have operator overloading at all? const a = 2n const b = 8n const c = 6n a + b - c == 4n // Looks like real JS a.plus(b.minus(c)).equals(4n) // Looks like a hot mess. But why give userland operator overloading? Allows community to define what would be useful in std lib (Date, Vector, Point, Coords, Color) Userland can polyfill newer data types


The simple answer is that JavaScript allows access to children of an Object via the square brackets.

So you could define your class:

MyClass = function(){
    // Set some defaults that belong to the class via dot syntax or array syntax.
    this.some_property = 'my value is a string';
    this['another_property'] = 'i am also a string';
    this[0] = 1;
};

You will then be able to access the members on any instances of your class with either syntax.

foo = new MyClass();
foo.some_property;  // Returns 'my value is a string'
foo['some_property'];  // Returns 'my value is a string'
foo.another_property;  // Returns  'i am also a string'
foo['another_property'];  // Also returns 'i am also a string'
foo.0;  // Syntax Error
foo[0];  // Returns 1
foo['0'];  // Returns 1

Fake operator overloading in JavaScript, looks at the addition operator in more detail. This post describes how to do a limited version of operator overloading in JavaScript. With the  The closest thing you can achieve in JavaScript is fake operator overloading – triggering two method calls: obj1.valueOf() obj2.valueOf() Those are made because + only works with primitive values and thus needs to convert obj1 and obj2 to primitives.


Use a proxy. It was mentioned elsewhere in the answers but I think that this is a better example:

var handler = {
    get: function(target, name) {
        if (name in target) {
            return target[name];
        }
        if (name == 'length') {
            return Infinity;
        }
        return name * name;
    }
};
var p = new Proxy({}, handler);

p[4]; //returns 16, which is the square of 4.

tc39/proposal-operator-overloading, Should JavaScript support operator overloading? b) { return a.contents.length === b.contents.length && a.contents.every((elt, i) => elt == b.contents[i]); }, "[]"(a,  Output streams use the insertion ( <<) operator for standard types. You can also overload the << operator for your own classes. The write function example showed the use of a Date structure. A date is an ideal candidate for a C++ class in which the data members (month, day, and year) are hidden from view. An output stream is the logical


As brackets operator is actually property access operator, you can hook on it with getters and setters. For IE you will have to use Object.defineProperty() instead. Example:

var obj = {
    get attr() { alert("Getter called!"); return 1; },
    set attr(value) { alert("Setter called!"); return value; }
};

obj.attr = 123;

The same for IE8+:

Object.defineProperty("attr", {
    get: function() { alert("Getter called!"); return 1; },
    set: function(value) { alert("Setter called!"); return value; }
});

For IE5-7 there's onpropertychange event only, which works for DOM elements, but not for other objects.

The drawback of the method is you can only hook on requests to predefined set of properties, not on arbitrary property without any predefined name.

Operator overloading, Operator overloading¶. ExtendScript allows you to extend or override the behavior of a math or a Boolean operator for a specific class by defining a method in  I don't actually think deviating from standard JS and implementing operator overloading is a good idea, but here's a thing I haven't heard anyone talk about:. As state in here, one of the problems with operator overloading proposals for ECMScript is the fact that it would require extensive type checks, something that could maybe be facilitated by TS's type system.


Why not Operator Overloading in JavaScript?, Operator Overloading is a special case of polymorphism, in which operators like +, /, *, can be overloaded by the user. This is very useful in  In C++, we can make operators to work for user defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator ‘+’ in a class like String so that we can concatenate two strings by just using +.


JavaScript 2.0 Operator Overloading, Wednesday, February 16, 2000. Overview. Operator overloading is useful to implement Spice-style units without having to add units to the core of the JavaScript  Operators Overloading in C++. You can redefine or overload most of the built-in operators available in C++. Thus, a programmer can use operators with user-defined types as well. Overloaded operators are functions with special names: the keyword "operator" followed by the symbol for the operator being defined.


Why, among these nice modernizing features in ES6, is operator , The bigger problem is that JavaScript is a dynamically typed language. Overloading operators will add a ton of work for the implementors of the specification to  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.