Even or Odd

We have the following code that should return only the odd numbers in reverse order that are in values...

(function() {
    var values = [3, 8, '15', Number.MAX_VALUE, Infinity, -23],
        oddValues = [],
        index,
        lenValues = values.length,
        isOdd = function ( value ) {
            return (value % 2) !== 0;
        };

    while(lenValues--) {
        if ( isOdd( values[lenValues] ) ) {
            oddValues.push( values[lenValues] );
        }
    }
    console.log( oddValues );
}());

...but when this code is executed we get [-23, Infinity, "15", 3].

Ah! Maybe Number.MAX_VALUE is a even number then why not substract 1 and check it again?

(function() {
    var values = [3, 8, '15', (Number.MAX_VALUE -1), Infinity, -23],
        oddValues = [],
        index,
        lenValues = values.length,
        isOdd = function ( value ) {
            return (value % 2) !== 0;
        };

    while(lenValues--) {
        if ( isOdd( values[lenValues] ) ) {
            oddValues.push( values[lenValues] );
        }
    }
    console.log( oddValues );
}());

...but when this code is executed we get [-23, Infinity, "15", 3] again.

Please explain why Number.MAX_VALUE has not been added:

Write the code to avoid Infinity to be added.

Last updated

Was this helpful?