0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
goodvibration
  • 5,980
  • 4
  • 28
  • 61
  • I don't know what makes you think this is operator-overloading, BigNumber returns a number, the docs say that the quotes are because they called a preceding `.toString()`. You're subtracting 2 Numbers here – Sterling Archer Jan 30 '18 at 19:50
  • I checked it via `console.log(typeof a)` and got `Object`, not `Number`. – goodvibration Jan 30 '18 at 19:53
  • Possible duplicate of [Overloading Arithmetic Operators in JavaScript?](https://stackoverflow.com/questions/1634341/overloading-arithmetic-operators-in-javascript) – Ele Jan 30 '18 at 19:54

1 Answers1

3

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
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445