1

I have this code, that works:

function getSomeValue(property) {
    var obj = {
        lvl1: {
            lvl2: {
                lvl3: 'hi'
            }
        }
    };
    //Is it ok to use eval?
    return eval('obj.' + property);
}

//I would like to return the value of obj.lvl1.lvl2.lvl3 
getSomeValue("lvl1.lvl2.lvl3");

It is the first time I feel the need to use eval. Is eval evil? Is there another quick way to achieve this?

JMaylin
  • 1,378
  • 4
  • 15
  • 38

2 Answers2

4

You don't have to use eval, for example:

    function getSomeValue(property) {
      var obj = {
          lvl1: {
            lvl2: {
              lvl3: 'hi'
            }
          }
        },
        arr = property.split('.');

      return arr.reduce(function(a, b) {
        return a[b];
      }, obj);
    }

    document.write(getSomeValue("lvl1.lvl2.lvl3"));
CD..
  • 72,281
  • 25
  • 154
  • 163
1

Personally I think this is fine, because you are limiting what can be evald to what's in the obj.

Use of eval is bad when you are running code derived from an AJAX call on a remote server, or some other external script. Also, there's no change or manipulation of the window object here, so I don't see the issue.

Assuming you're passing code around as strings, you have to question whether you need to do that and what value it offers your application. But I guess, why not if you want to.

Alex
  • 4,844
  • 7
  • 44
  • 58
  • But if there's any chance that the parameter to `getSomeValue()` is not a constant and it comes from untrusted source, the attacker can pass `"foo; alert( 'haxxor' )"` and boom. – JJJ Nov 18 '14 at 11:57
  • They could on their local machine, wouldn't do them much good though. Unless they hacked the server password. But then it's game over anyway, and they have full control. – Alex Nov 18 '14 at 12:21
  • It could be something from e.g. a database. Let's assume, for example, that for some reason Stack Overflow eval'd the contents of your profile. You could then add JS code to your information field and anyone viewing your profile would get hit. – JJJ Nov 18 '14 at 12:25
  • Perhaps, although in that case you'd want to JS escape all database output. `eval` is used by various frameworks and plugins in order to read properties (I have seen it being used in require.js for example). Just never in a scenario where remote code could be evaluated. – Alex Nov 18 '14 at 12:30