Hello Folks 👋
What’s up friends, this is SnowBit here. I am a young passionate and self-taught developer and have an intention to become a successful developer.
Today, I am here again with a crazy thing in JavaScript.
So, let’s get started.
console.log(Math.max())
As we all know the biggest positive number is ∞ (infinity). So the out of the above code snippet should be positive Infinity
. For better understanding, you can see the attached graph
console.log(Math.max())
// -Infinity
But, as we know JavaScript is crazy 🤪; The output of this code is -Infinity
. Don't believe it? check out the demo - https://jsfiddle.net/ce0hkoLs/
Now, here come Math.min()
it is converse of Math.max
As we all know that lowest negative number is -∞(-infinity), but we know that’s not the case.
console.log(Math.min())
// Infinity
We all know simple math, right? Now again we have a crazy thing with mathematics in JavaScript.
console.log(0.5 + 0.1 == 0.6)
// true
Yes, 0.5 + 0.1 == 0.6
is true, isn’t it?
Now here comes some thing crazy,
console.log(0.1 + 0.2 == 0.3)
As we know, 0.1 + 0.2 == 0.3
is true, but JavaScript don’t think that. Somehow, JavaScript thinks it is false, I actually don’t know the exact reason for that let me know in the comments if you know it.
There, the output will be,
console.log(0.1 + 0.2 == 0.3)
// false
Try it - https://jsfiddle.net/feahj1s2/
Thank you for reading, have a nice day!
Your appreciation is my motivation 😊
- Follow me on Twitter - @codewithsnowbit
- Subscribe to me on YouTube - Code With SnowBit
Top comments (4)
It actually makes a lot of sense that the maximum of nothing is the lowest possible number.
Consider this example:
Consider now that
a = []
andb = [2]
If
Math.max(...[])
, which is the same asMath.max()
returned positive infinity, then the first example would beMath.max(Math.max(), Math.max(2))
which would return positive infinity, even though the second example would return 2 becauseMath.max(...[], ...[2])
is the same as justMath.max(2)
.The second one is really just the age-old topic of floating point inaccuracy. It's interesting to explore why it happens with one set of numbers but not with another, but on its own, it's really just a well-known phenomenon.
As for the second point, it is not really a JavaScript issue - rather it is an issue with the way floating point (decimal) numbers are stored internally. This website gives a fairly succinct explanation and examples of the issue in various languages.
haha, website is amazing specially url
Great explaination!