Search code examples
javascriptinfinity

Can I use Infinity and -Infinity as an initial value for Max and Min variables?


I thought that it would be acceptable to initialize my Max value to -Infinity but this did not turn out to be the case in JavaScript.

If Infinity is considered a number type why can't I use it in my comparisons?

  var windowStart =0, sum =0, max = -Infinity
  for(windowEnd=0;windowEnd<k-1;windowEnd++)
  {
    sum += arr[windowStart]
    if(windowEnd>k-1)
    {
      if(sum > max)
        max = sum
      sum -= arr[windowStart]
      windowStart += 1
    }
  }

  return max;

Thanks to the community I noticed that I jumped the gun in posting my question and did not do an appropriate amount of my own debugging. Thank you all for your quick answers.


Solution

  • You can use Infinity as you intended:

    Math.min(Infinity, 10)
    // => 10
    
    Infinity < 10
    // => false