Over the last two posts I’ve been describing JavaScript’s ability to have language key words as object keys. Perhaps surprising to no one is that this is achieved via string coercion. However the coercion isn’t being done by the developer using some shady technique, but by the language itself. Nowhere is this more evident than by trying to use language key words as object keys. The following code will result two in a successful look-ups:

var x = true;
var y = "true";
var obj = {
  true: "yup"
};
obj[x]; //  "yup"
obj[y]; //  "yup"

The downside of this, of course, is that you can’t create an object that would treat those two values differently. In other words, all that’s happening in the code below is one value is being set twice:

var obj = {
  true: "yup",
  "true": "Yes"
};

console.log (obj); // {true: "Yes"}

But there is an upside as well: APIs that return all values as strings or ones that return synonyms for values (eg, “Yes” instead of “true”) don’t need to have logic applied to transform them into proper values.

var boolCases = {
  true: true, // valid for both the value and the string
  false: false,
  Yes: true,
  No: false,
  undefined: false,
  null: false
};

var fixedVal = boolCases[apireturn.someboolkey];

The boolCases object can now be read as a literal mapping between the API’s definition of Boolean values and JavaScript’s. Further, it even handles the case where the API hands back nothing, and all without logic, only look-ups.

Regardless of this or any other use case, JavaScript will coerce its protected language key words into strings for the purposes of an object look-up.

Thanks to @b_rendan for helping me uncover what was happening with this technique.