Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crazy javascript problem: undefined actually !== undefined!

Before anyone asks, I have already search existing questions and found this question, but the answer was that undefined was being set to null, which is not the case here.

Here is my code:

check_availability = function () {
    var value = $('#contact_type').val();
    if (value !== undefined) {
        // do some stuff
    }
}

Simple huh? I have a <select id="contact_type"></select> with options populated via ajaxy stuff. Initially the options list is empty, so the jQuery val() returns undefined. So far so good.

Except that the code within the if block always executes. I stick a breakpoint in FireBug on the 3rd line and I get this:

undefined weirdness

Can anyone tell me what's going on?

P.S. This is Firefox 4.0


EDIT: I know there are a number of ways I can achieve the same result, I'm more interested in why value is undefined according to FireBug, but then is !== undefined.

like image 625
stusherwin Avatar asked Dec 08 '25 23:12

stusherwin


2 Answers

Just check the truthiness of value.

if (value) {
    // sexy times
}

BTW, jQuery returns null, not undefined, when the <select> contains no <option>s. http://jsfiddle.net/mattball/cQ83z/

like image 156
Matt Ball Avatar answered Dec 11 '25 12:12

Matt Ball


The val() is never undefined: http://jsfiddle.net/ThiefMaster/UmZhG/

If the <select> has no options, it is null; otherwise there's always an option selected.

Fyi, value == undefined is true since null == undefined (even though null !== undefined)

like image 31
ThiefMaster Avatar answered Dec 11 '25 13:12

ThiefMaster