2

I've searched the web for what eval does and here is what I have found:

The eval() method evaluates JavaScript code represented as a string.

And I've read this question, which says that it is evil.
But I really don't understand what does it do, i.e I don't see when to use eval.
I mean:

var x= 3;
var y =5;
var z = eval("x+y");
// is the same as:
var z = x+y;

so as I see it's just adding characters to my code. Can somebody give me an example of why eval was created in the first place?

Community
  • 1
  • 1

2 Answers2

3

It allows execute dynamicly generated code, not just "x+y".

Daniil Grankin
  • 3,841
  • 2
  • 29
  • 39
1

Eval allows you to evaluate a string as javascript code. This means you can do things like evaluate a string to call a function:

function add(x,y){
     return (x+y);
}

stringToEval = 'add(5,6)';

eval(stringToEval);

This code would run the function by evaluating the string as a function call. So I would say you do not need to use eval here. Just add the two variables.

A_Sandwich
  • 97
  • 2
  • 10