0

Curious as to what unforeseen issues this type of code might present, if executed on the server. Or if there are any non eval alternatives.

var a = {b:1, c:2, d:3, e:[1,2,3]};
(function(path) { return eval('this'+path) }).call(a, '.e[2]');
12
  • where does path come from? besides, return this[path] works Commented Jun 1, 2015 at 18:46
  • path comes in a param from client. Commented Jun 1, 2015 at 18:47
  • Are you sure this[path] works? Commented Jun 1, 2015 at 18:48
  • 1
    then it's very dangerous, slow, and unneeded, just use the array syntax shown. Commented Jun 1, 2015 at 18:48
  • 1
    don't play cat and mouse. do yourself a favor just get rid of the eval and use a resolve(). look up how to access object properties by a string, it's been answered a lot. godspeed. Commented Jun 1, 2015 at 19:19

1 Answer 1

1

Given that path is a static value (".e[2]") and a does not have any malicious accessors or so, there is nothing insecure here except that it's totally unnecessary.

However, if path does come from a client or some other untrusted source, then passing it to eval is the worst thing you can do. It can do everything that JS code can do in node - and that is enough to harm you severely.

And yes, there are tons of non-eval alternatives.

Sign up to request clarification or add additional context in comments.

3 Comments

comments state that path is a value passed in from the client so it is far from static or secure.
@NeilSmithline: Thanks, this wasn't stated in the question. Updated my answer for that case.
Yes, I ended up going with lodash 3.9.*'s _.get() which does exactly what I need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.