Mathieu Mourareau
Mathieu Mourareau

Reputation: 1220

Javascript number comparison with negative value doesn't work

I try to compare a negative value with "0" and that doesn't seem to work.

var number = Number.parseInt($(this).val());
var min = Number.parseInt($(this).attr('min'));
var max = Number.parseInt($(this).attr('max'));

Here's my condition :

if (min && $(this).prop('required')) {
    if (number < min) {
        alert('ok');
            fail = true;
    }
}

My min value is 0 and my number is -1.

It never enters the condition. Why?

Upvotes: 0

Views: 92

Answers (4)

yehonatan yehezkel
yehonatan yehezkel

Reputation: 1248

(0 && true ) return zero in JavaScript. see first comment for more details

Upvotes: 0

jo_va
jo_va

Reputation: 13964

Since min is 0, your condition evaluates to false. You have two options, one is to check the string value before parsing it:

if($(this).attr('min').trim() && $( this ).prop('required')) {
    if (number < min) {
        alert('ok');
        fail = true;
    }
}

The other is to check for NaN after parsing the number since parsing an empty string will return NaN:

if(!isNaN(min) && $( this ).prop('required')) {
    if (number < min) {
        alert('ok');
        fail = true;
    }
}

console.log('  '.trim() == false);
console.log(!isNaN(Number.parseInt('')) == false);

Upvotes: 2

adiga
adiga

Reputation: 35202

0 is a falsy value. It will never enter the if condition if min is 0 .

All the following conditions will be sent to else blocks

if (false)
if (null)
if (undefined)
if (0)
if (NaN)
if ('')
if ("")
if (``)

Since the return value of parseInt is either a number or NaN, you can use isNaN instead:

if(!isNaN(min) && $(this).prop('required')) {
  // your code
}

Upvotes: 5

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

Your condition:

if(min && $( this ).prop('required'))

Would evaluate to false since min has a value of 0 and 0 && anything would be false

Upvotes: 1

Related Questions