So I'm a JS newbie and am trying to figure out how to fix my problem. I am trying to loop over an object and return the lowest number.
in my var shortest = ;
if I hardcode a number say var shortest = 455;
then the problem returns the correct number 3. although im not sure what to put there to make it blank by default. I have tried object[0]
, object[key]
and ''
and none of these work properly
var myObj = {first: 45, second: 23, third: 3, fourth: 222, fifth: 2343};
var myFunc = function (object) {
var shortest = ;
for (var key in object) {
if (object[key] < shortest) {
shortest = object[key];
}
};
return shortest;
};
Try this:
set initial value of shortest to Number.MAX_VALUE is all you need
Number.MAX_VALUE The largest positive representable number.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
See if this helps:
The reason it fails is in here:
Since the value of shortest is undefined, the
<
operator causes it to be converted toNaN
for the test, and according to the rules for The Abstract Relational Comparison Algorithm, comaring anything toNaN
returns undefined, which is equivalent tofalse
here.The fix is to initialise shortest to some value, e.g. as qiu-deqing suggested Number.MAX_VALUE, or you can use something like:
The above will ensure that you only compare numbers and that shortest will only be a number or undefined. There should probably be a hasOwnProperty test too to avoid inherited properties.