Phil
Phil

Reputation: 3562

Javascript - MIN_VALUE vs MIN_SAFE_INTEGER vs -Infinity

I recently ran into an error where I did this expression:

Math.max(Number.MIN_VALUE, 0)
// returns 5e-324

I'm not quite sure how it returned this value, so I tried inverting the expression to see what would happen:

Math.min(Number.MAX_VALUE, 0)
// returns 0

This works fine however..

The way I fixed the first expression is by doing this:

Math.max(Number.MIN_SAFE_INTEGER, 0)
// returns 0

A few questions:

  1. Why does taking the MAX of Number.MIN_VALUE and zero equal 5e-324?
  2. If we have Number.MIN_SAFE_INTEGER should we always use this or is there a use case for Number.MIN_VALUE?
  3. If I am just using MIN/MAX values as an initial state (that will for sure be overwritten on the first comparison), should I use -Inifinity / Infinity instead?

Upvotes: 2

Views: 1815

Answers (1)

Maheer Ali
Maheer Ali

Reputation: 36584

Why does taking the MAX of Number.MIN_VALUE and zero equal 5e-324

Because Math.MIN_VALUE is not the lowest negative value. Its minimum positive value. So all the positive values are greater than 0 that's why it return 5e-324 instead of 0

If we have Number.MIN_SAFE_INTEGER should we always use this or is there a use case for Number.MIN_VALUE?

I can't think of any use case for Number.MIN_VALUE because its not safe. It can create wrong calculations in code.

If I am just using MIN/MAX values as an initial state (that will for sure be overwritten on the first comparison), should I use -Inifinity / Infinity instead

It completely depends upon the purpose of the code.

Upvotes: 3

Related Questions