The easiest approach is to make a hash - no function is required.
var states = { 'AL': 'Alabama', 'AK': 'Alaska', 'AZ': 'Arizona', 'AR': 'Arkansas', 'CA': 'California', 'CO': 'Colorado', 'CT': 'Connecticut', ... 'WY': 'Wyoming' }; var stateName = states["WY"];
EDIT
Now I better understand that getState() needs to get state names from the server. This puts you in the world of asynchronous coding, which is very different from regular synchronous coding.
The most important thing to understand is that getState() cannot just return the state name for this abbreviation. What for? Since the ajax call on the server is asynchronous - in other words, getState() will not wait for the server to respond before returning.
There are two approaches to handling asynchrony:
- pass the callback function (s) to
getState() to tell what to do when the response is received - arrange
getState() to return a special type of object called a "promise" that can be processed where getState() is called so that it will respond when the server responds.
The code below uses the second approach.
var states = {};//cache of state names, with state abbreviations as keys function getState(abbr) { var dfrd = $.Deferred();//A deferred object, whose promise will be returned. if(!states[abbr]) { $.ajax({ url: "states.asp", dataType: 'XML', success: function(data) { //Load up the cache $.each($('state', data), function(i, el) { states[el.attr('abbr')] = $(el).text(); }); //Now resolve or reject the deferred object depending in whether states[abbr] has been cached if(states[abbr]) { dfrd.resolve(abbr, states[abbr]);//Success! Let resolve the deferred object (and its promise). } else { dfrd.reject(abbr, 'States successfully downloaded but ' + abbr + ' was not included'); } }, error: function() { dfrd.reject(abbr, 'Download of states failed'); } }); } else { //The state name is already cached //The deferred object (and its promise) can be resolved without needing to make another ajax call. dfrd.resolve(abbr, states[abbr]); } return dfrd.promise(); }
untested
Now all you have to do is call getState() .
getState("WY").done(function(abbr, state) { alert(abbr + ': ' + state); //other stuff here }).fail(function(abbr, message) { alert(abbr + ': ' + message); //other stuff here });
As you can see, the value you wanted getState() to return now appears as the second argument to the .done() function. For good measure, the abbreviation ("WY") appears as the first argument.
If you want to handle error conditions (always a good idea) then do it in the .fail() .
See the comments in the code for more details on how everything works.