Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 897
EmmyS Avatar asked Jun 05 '26 11:06

EmmyS


1 Answers

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

Use === instead of ==.

like image 184
nnnnnn Avatar answered Jun 07 '26 00:06

nnnnnn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!