0

i know this function gets a string of valid JavaScript expression or statements and evaluate the expression or execute the statements, but why we need to pass code to a function for execution instead of simply writing the code in the script?

MTVS
  • 2,046
  • 5
  • 26
  • 37
  • for example for using json in browser don't have the json-object. Or for calculating some input. – Sindhara Jun 04 '12 at 14:37
  • Take a look at this: http://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea – Someth Victory Jun 04 '12 at 14:38
  • 1
    Possible duplicate of http://stackoverflow.com/questions/1594023/what-is-the-intended-purpose-of-eval-in-javascript – sv_in Jun 04 '12 at 14:38

3 Answers3

2

Sometimes code is constructed dynamically, or it's something like JSON that needs to be evaluated in the current context, etc. Doing so isn't necessarily good, or necessary--a different discussion.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
2

It depends on situation where you need to create dynamic variables or even parse json data. Whatever the case, it is highly recommended NOT to use it.

See more explanation at:

To avoid it, see;

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
1

Let's say you have functions: makeCheckbox(), makeRadio() and makeSelect() (theoretically). You want to call function by user's activity (for example menu click). You can make it with if, else if and so on, you can make switch, but you can eval too and make something like:

eval('make'+userChoose.charAt(0).toUpperCase()+string.slice(1)+'()');

where userChoose is one of the options: radio,checkbox or select, which is first-char-uppercased first and then concatenated with make (before) and () (after), which at the end calls one of the functions.

This is not good practice because in large projects you can't simply find callings to function, because they're "hidden behind" eval, but sometimes it's the only way.

Community
  • 1
  • 1
Wirone
  • 3,304
  • 1
  • 29
  • 48