Categories
JavaScript

eval() is evil: window to the rescue

In JavaScript eval() has long known to be evil. Take for example:

function foo(){}
foo["str1"] = "aaaa";
foo["str2"] = "bbbb";
foo["str3"] = "ccccc";

Elsewhere you need to lookup items from this structure. Where both “foo” and “str1” are pass in as arguments. So like:

function lookUp(bundle, str) {
return eval(bundle[str]);
}

eval() will invoke a new scope and new compiler just to find and evaluate the string values. There must be a better way. Since foo is defined previously it’s available via the window object. So you can simply say:

function lookUp2(bundle, str) {
return window[bundle][str];
}

Pretty simple eh?

Kevin Henrikson
Kevin Henrikson leads engineering for Microsoft Outlook iOS/Android. Previously, he co-founded Acompli and ran engineering prior to an acquisition by Microsoft in 2014 for $200M. Before Acompli, he was an Entrepreneur-in-Residence for Redpoint Ventures, a venture capital firm for early stage technology companies.

By Kevin Henrikson

Kevin Henrikson leads engineering for Microsoft Outlook iOS/Android. Previously, he co-founded Acompli and ran engineering prior to an acquisition by Microsoft in 2014 for $200M. Before Acompli, he was an Entrepreneur-in-Residence for Redpoint Ventures, a venture capital firm for early stage technology companies.