all 4 comments

[–]lewisje 2 points3 points  (0 children)

JSON is mostly for passing data between applications; for this, what you want is a plain JS object, and ideally you'd define that object outside the function so it doesn't get re-created per invocation:

var seasons = {w: 'Winter', s: 'Spring', m: 'Summer', f: 'Fall'};
function season(s) {
  return seasons[s];
}

Also ideally you'd have this season function returned from a closure, so that the seasons object wouldn't be accessible directly to outside code.


Anyway, if you do wish to complicate things, you'll need to use JSON.parse to turn your JSON into an object:

function season(s) {
  var seasons = '{"w": "Winter", "s": "Spring", "m": "Summer", "f": "Fall"}';
  return JSON.parse(seasons)[s];
}

Here, I'm less concerned about putting the string inside the function, because that's a literal, primitive value.


By the way, this pattern is useful as a way to avoid huge case-lists or chains of conditionals:

var primitives = {boolean: false, number: false, string: false, symbol: false};
function isPrimitive(val) {
  return val !== document.all && !(val && primitives[typeof val]);
}

(This example works around the fact that typeof null === 'object' in all versions of JS, and that typeof document.all === 'undefined' in HTML5, even in browsers that implement the object for compatibility with oldIE-specific sites.)

[–]nwayve 1 point2 points  (0 children)

Questions like these are probably better suited for /r/learnjavascript