views:

89

answers:

4

I have this object/array thing:

var states = {};

states["CA"] = new State("CA", "California");
states["AR"] = new State("AR", "Arizona");
....

How can I check if states["AL"] has been set or not? Will the following work (in all browsers)?

if (states["AL"] == undefined)
   alert("Invalid state");
+2  A: 

Recommended:

if (typeof states["AL"] == 'undefined')
    alert("Invalid state");

Litteral undefined is possible and will work most of the time, but won't in some browser (IE mac, maybe others).

streetpc
undefined should be in quotes?
Click Upvote
Yes, because `typeof` returns a string. However, I'm not sure why using `typeof` is better in the first place.
Matt Ball
@streetpc What if states["AL"] is null? Then `typeof states["AL"]` will return `"object"` and you won't handle an invalid value correctly.
Jonathon
@Jonathon: What was asked was whether `states["AL"]` has been set. It being set it to `null` still counts as being set. @Bears: `typeof` is better for two reasons: one, in some older browsers, the global object doesn't have an `undefined` property, and two, because `undefined` is a property of the global object rather than an immutable literal like `null`, it can be inadvertently redefined. For example, a typo in an equality check could do it: `if (undefined = someVar) {...}`.
Tim Down
+2  A: 

You don't have to do a literal comparison at all; the following will work just fine...

if(states["AL"]) 
  alert("State exists"); 
else
  alert("State does not exist"); 
Josh Stodola
really? will that work in all browsers?
Click Upvote
@Click Yes, if states["AL"] has not been set it will return undefined which will evaluate to false in a boolean expression.
Jonathon
@Click Yes, Jonathon is right.
Josh Stodola
I would not recommend that for this particular test. What you have above checks if `states["AL"]` is a truthy value or not - for instance `states["AL"]` might be set to `false` but that's different from being undefined.
Matt Ball
so if i did `if (! states["AL"])` would that work as well?
Click Upvote
@Click - http://11heavens.com/falsy-and-truthy-in-javascript
Matt Ball
@Bears This seems ok to me. If states["AL"] is any sort of valid value (non-empty string that doesn't evaluate to false), this will handle it fine.
Jonathon
This checks for true/false. So if `states["AL"]` is zero, it will return false, which is technically not what you want.
James Wiseman
Well, it depends on what the intent of the check is. It sounded like the OP wanted to see whether or not an entry is defined at all - not check to see if it is a falsy value.
Matt Ball
A: 
function State(ab, name){
    if(states && states[ab])return states[ab];

    this.ab=ab;
    this.name=name;
    //whatever else, no return;
}
kennebec
+1  A: 

Alternately, you could say if ("AL" in states) { ... }.

Sean