0

When dividing in JS you get Infinity if you divide by zero, I want to change that behavior by returning undefined so I can identify a real Infinity vs. an error result.

Assuming that writing the next line calls some math or build-in function for division:

var a = 6 / 0;
  1. What is the full name/path of the '/' function ?
  2. Is there a way to overwrite it (or any other operand)?

A sharpening:

Infinity / 1 = Infinity (the top Infinity is a result from a devision by zero) whereas undefined / 1 = Nan. Is it possible without writing and using my own function to identify that there was a problem in during the calculation?

Avishay
  • 305
  • 1
  • 11

2 Answers2

1

/ is not a function in JavaScript, it's an operator, so you can't override it.

You can, however, write a function to protect division:

function divide (a, b) {
    return b === 0 ? undefined : a / b;
}

and use it like so:

var a = divide(6, 0);
Eliran Malka
  • 15,821
  • 6
  • 77
  • 100
0

That is just an arithmetic operator that is used for division purposes.

You cannot override it. However, you can use an if else block to check for the infinity value, and change it to undefined.

Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103