Yann Chabot
Yann Chabot

Reputation: 4879

What is NEGATIVE_INFINITY for in Javascript

I got this in a function I found on internet, but I can't understand what it's for. What I've read on W3school.com. Here is how they explain it:

Negative infinity can be explained as something that is lower than any other number.

So this is something I can understand but I can't think of a moment where you'd need this kind of constant. Plus, check this function out:

function setEqualHeight(selector, triggerContinusly) {

  var elements = $(selector)
  elements.css("height", "auto")
  var max = Number.NEGATIVE_INFINITY;

  $.each(elements, function(index, item) {
      if ($(item).height() > max) {
          max = $(item).height()
      }
  })

  $(selector).css("height", max + "px")

  if (!!triggerContinusly) {
      $(document).on("input", selector, function() {
          setEqualHeight(selector, false)
      })

     $(window).resize(function() {
          setEqualHeight(selector, false)
     })
  }
}

I understand the whole function. But I can't figure out why would max be = Number.NEGATIVE_INFINITY at first. Then, he check if the height is higher then the smallest possible number?

This function works perfectly so I'm guessing it's correct but I really don't understand what is the usage in this function or why would people use this in general.

I hope you guys will be able to enlighten me !

Upvotes: 0

Views: 8458

Answers (2)

azeem
azeem

Reputation: 361

Negative Infinity is not a Rocket Science. Its a reverse of positive infinity.

var i=-3/0;
Ans= -Infinity

Upvotes: 2

Austin Brunkhorst
Austin Brunkhorst

Reputation: 21130

It's common to use extreme values as a starting point for functions finding the maximum in a set of data. In this case, because elements don't have a height less than 0, it isn't necessary, but provides better understanding once you've seen this concept before.

Consider the following arbitrary example.

var data = [ 1, 5, -10000, 50, 1240 ];

function maxData(data) {
    var max = Number.NEGATIVE_INFINITY;

    for (var i = 0; i < data.length; ++i)
        if (data[ i ] > max)
            max = data[ i ];

    return max;
}

This works great in JavaScript because any value compared to Math.NEGATIVE_INFINITY will be greater.

In other languages like C++, it's common to use the minimum value of an integer, float, etc.

Upvotes: 6

Related Questions