EmmyS
EmmyS

Reputation: 12138

javascript IsNaN and 0

I have some code that's returning unexpected results.

HTML:

<select name="cc_dropdown[0]" id="cc-dropdown-0" style="display: none;">
    <option value="">Select a card</option>
    <option value="0" selected="selected">***********8431</option>
    <option value="-1">Use a new card</option>
</select>

JS:

var ccVal = parseInt($("#cc-dropdown-0 option:selected").val());
var errors = [];

if( ccVal == -1 ) {
        if( $('#cc_number-'+bIdx).val().length <= 0 || !isValidCreditCardNo($('#cc_number-'+bIdx).val()) ) {
            errors.push('Invalid Credit card Number');
        }

        if( $('#cc_name-'+bIdx).val().length <= 0 ) {
            errors.push('Please provide the name on the credit card.');
        }

        if($('#cc_exp_month-'+bIdx).val() == ""){
            errors.push('Please Select an Expiration Date.');
        }

        if($('#cc_exp_year-'+bIdx).val() == ""){
            errors.push('Please Select an Expiration Date.');
        }

        if( !isValidZipcode($('#cc_zip-'+bIdx).val())){
            errors.push('Please enter a valid zipcode.');
        }
    }    else if ( ccVal == 'na' || ccVal == '' || isNaN(ccVal)) {
        console.log("ccVal inside else if: " + ccVal);
        console.log("ccVal type: " + typeof ccVal);
        errors.push('Please select a credit card, or enter a new one.')
    }
else {
    console.log("else");
    errors.push("Arg!");
}
console.dir(errors);

In this case, ccVal is 0, and yet it's falling into the else if statement. I would expect that to happen only if it's not a number at all. Expected result is that it should fall into the final else statement. Here's a JSFiddle with the results: http://jsfiddle.net/n2Uy7/

Can anyone explain why this would be the case? If it's 0, it should not hit either the if or the else if statements. Does JS consider 0 to be NaN, even though typeof indicates that it is a number?

Upvotes: 3

Views: 4853

Answers (2)

Jon
Jon

Reputation: 437376

You are comparing with "just" double equals signs, so 0 == '' (try it in your browser's console).

One way to fix the issue is to use triple equals instead. Another way is to remove the parseInt entirely, so ccVal will remain a string. String to string comparisons will then behave as expected ('' != '0').

Removing the parseInt would also solve another issue (you are not passing in the radix, but you must). Why is it there anyway?

Upvotes: 2

nnnnnn
nnnnnn

Reputation: 150030

0 == '' is true so the isNaN part doesn't even get evaluated.

Use === instead of ==.

Upvotes: 7

Related Questions