goodvibration
goodvibration

Reputation: 6206

Am I witnessing operator-overloading in JavaScript?

I thought that there was no such thing as operator-overloading in JavaScript.

Then I noticed that when using this BigNumber class, I can actually do subtraction:

let a = new BigNumber("5432");
let b = new BigNumber(1234);
let c = a - b;
console.log(c); // 4198

How is it possible, or what am I missing here?

Upvotes: 0

Views: 120

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 190976

JavaScript doesn't have operator overloading.

BigNumber.prototype.valueOf is provided which returns a value. Read up on valueOf.

From MDN:

function MyNumberType(n) {
    this.number = n;
}

MyNumberType.prototype.valueOf = function() {
    return this.number;
};

var myObj = new MyNumberType(4);
myObj + 3; // 7

Upvotes: 3

Related Questions