Why does Javascript return Infinity instead of error when dividing by 0?

6

When I divide any value by zero, Javascript returns me Infinity .

My question is why Infinity ? Infinity is defined in Javascript, but I could not find a use for it in any case.

Can someone tell me too, what would be the use of it?

    
asked by anonymous 21.06.2017 / 16:21

3 answers

8

When dividing something by zero you have to have some way to represent it in JavaScript. This is the main reason for its existence: the representation of a mathematical entity.

Another case, imagine that you need to know the smallest number of a given array you have, it is useful to have a variable that is "unbeatable" to be able to change the smaller value:

var arr = [345435, 1, 744, 78899, 3e500];
let menor = Infinity;
for (let nr of arr) {
  if (nr < menor) menor = nr;
}

console.log(menor);
    
21.06.2017 / 16:29
5

I would like to add information that does not appear in @Sergio's answers (which gave a great example of using Infinity ), and @LeoCaracciolo (which explained how division by zero tends to infinity - can be infinite negative too , if the dividend is negative).

What I wanted to clarify is that this logic is not a direct decision of the language project, but indirect. All numbers in JS are represented as floating points, and the floating point arithmetic (IEEE 754) specification dictates that division by zero must be treated in this way. The use of exceptions and other types of "traps" ( traps ) in these cases is optional, the default is to return ±Infinity .

The specification FAQ justifies this as follows (free translation):

  

The standard 754 model encourages the creation of robust programs. It is geared not only to numerical analysis, but also to spreadsheet users, databases and even coffee makers. The rules of propagation of NaNs and infinitudes allow irrelevant exceptions to disappear (...). When exceptional situations require treatment, they can be examined immediately via traps , or at a more convenient time via status flags.

    
21.06.2017 / 22:17
2

To answer your question "My question is why Infinity?"

I do not know exactly if in javascript you made use of this reasoning to reach the value Infinity of the division of any value by zero.

1/0,1 = 10
1/0,01 = 100
1/0,001 = 1000
1/0,0001 = 10000
1/0,00001 = 100000
...................
...................

The divisor, the closer to zero, the greater the result of the division, that is, a very large, gigantic, inexplicably huge number, As for the use vide answer of the friend and King of the Javascript Sergio

    
21.06.2017 / 19:12