Shane Larson
Shane Larson

Reputation: 57

Javascript undefined issue

            if(typeof(GUEST_IDS) != undefined){
          GUEST_IDS = GUEST_IDS.substr(1);
          GUEST_IDS = GUEST_IDS.split(",");
          for(GP in GUEST_POINTS){
            GUEST_ON = 0;
            for(GID in GUEST_IDS){
              if(GUEST_IDS[GID] == GP){
                GUEST_ON = 1;
              }
            }
            if(GUEST_ON == 0){
              GUEST_POINTS[GP].setVisible(false);
            }
          }
        }else{
          for(GP in GUEST_POINTS){
            GUEST_POINTS[GP].setVisible(false);
          }
        }

when I alert GUEST_IDS it says undefined, so if GUEST_IDS = undefined why is the code running as if if(typeof(GUEST_IDS) != undefined){ is true?

Upvotes: 0

Views: 295

Answers (1)

pimvdb
pimvdb

Reputation: 154968

typeof returns a string specifying the type. Also, typeof does not require parens, and it's good practice to use !== over !=:

if(typeof GUEST_IDS !== "undefined") {

Other points:

  • Don't capitalize everything
  • Use var
  • Use a normal for loop to iterate over an array; not a for in loop
  • Don't overwrite existing variables; GUEST_IDS is changing from a string to an array
  • Use === rather than ==
  • You can use chaining like var ids = GUEST_IDS.substr(1).split(",");

Upvotes: 2

Related Questions