Reputation: 1373
Description: I am working on some exercises to get familiar with Javascript. One of the question asks me to find the smallest number in a given object below.
var myObj = { key: [5, 8, 1, 4] };
I set my initial value of smallest
to POSITIVE_INFINITY
and MAX_VALUE
.
After I ran my program (see below), undefined
was returned. However, when I set smallest
to 99999
, the program is executed correctly.
My Question: What causes undefined returned when I set my variable, smallest, to POSITIVE_INFINITY and MAX_VALUE ? Thank you in advance for your help.
var myObj = { key: [5, 8, 1, 4] };
function getSmallest(obj, key) {
//var smallest = Math.POSITIVE_INFINITY; //---> undefined is returned
//var smallest = Math.MAX_VALUE; //--->undefined is returned
var smallest = 99999; //---> Correct result is returned
if (!obj.hasOwnProperty(key) || !Array.isArray(obj[key]) || obj[key].length === 0) {
return undefined;
}
for (var i in obj[key]) {
if (obj[key][i] < smallest) {
smallest = obj[key][i];
}
}
return smallest;
}
var output = getSmallest(myObj, 'key');
console.log(output);
Upvotes: 0
Views: 113
Reputation: 2454
There is no MAX_INFINITY
constant in JavaScript. Even POSITIVE_INFINITY
would not fulfill the task correctly, because that is greater than MAX_VALUE
. However, you could simply use Math.min.apply
as mentioned in the comments.
If you really want to understand the logic behind JavaScript number constants, you could use NEGATIVE_INFINITY
, and see that it is less than all JavaScript numbers (including Number.MIN_SAFE_INTEGER
):
Number.NEGATIVE_INFINITY < Number.MIN_SAFE_INTEGER // true
Upvotes: 0
Reputation: 18933
Try this (use Number):
var max = Number.MAX_VALUE;
console.log(max);
var min = Number.MIN_VALUE;
console.log(min);
Upvotes: 0
Reputation: 77
Simply because it's Number.POSITIVE_INFINITY
, not Math.POSITIVE_INFINITY
. (Same for MAX_VALUE
)
Upvotes: 0
Reputation: 664936
The MAX_VALUE
and POSITIVE_INFINITY
constants are properties of the Number
object, not of Math
. You can also use the global Infinity
constant.
Upvotes: 2