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?

3
  • 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 Commented Jan 30, 2018 at 19:50
  • I checked it via console.log(typeof a) and got Object, not Number. Commented Jan 30, 2018 at 19:53
  • Possible duplicate of Overloading Arithmetic Operators in JavaScript? Commented Jan 30, 2018 at 19:54

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

6 Comments

I don't understand from your answer, how the expression a - b is executed / evaluated.
Oh, is it a.valueOf() - b.valueOf()?
So then I'm at risk losing precision in that case, right?
OK, I'll rephrase that: Speculating from the name "BigNumber", I'm at risk losing precision in your subjective opinion?
@General_Twyckenham: I used "-" by mistake, and my code was running flawless. Then I realized that I should have used "minus", so was wondering how come it worked without it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.