JavaScript Eval

JavaScript Eval

JavaScript Eval


In this chapter, you will see how a JavaScript built-ineval() function works. Normally, it is used for evaluating a JavaScript code, which is represented as a string.

The syntax of the eval() function is the following:

let result = eval(code);

For a better perception, you can check out the following example:

let code = 'console.log("Welcome to Web")';

eval(code); // Welcome to Web

Eval is considered a function property of the global object.

As a rule, the eval() function’s argument is a string. In case the latter presents an expression, eval()will evaluate it. In case an argument presents one and more statements, then eval()will evaluate the statements.

You shouldn’t call this function for evaluating an arithmetic expression, as JavaScript evaluates them automatically. In the cases when the argument is not a string, eval() will return the argument unchanged. Here is an example:

console.log(eval(new String('1 + 2'))); // returns a String object containing "1 + 2"

console.log(eval('1 + 2')); // returns 3

Such a limitation can be worked around with the help of toString() like this:

let exp = new String('1 + 2');

console.log(eval(exp.toString())); // returns 3

Generally, eval’s result is equivalent to the result of the last statement. It is demonstrated below:

let value1 = eval('1+2');

console.log(value1); // 3

let value2 = eval('let i = 1; ++i');

console.log(value2); // 2

In case the code is executed within the current lexical environment, outer variables can be seen by it:

let val = 1;

function fn() {

  let val = 10;

  eval('console.log(val)'); // 10

}

fn();

In addition, those variables can be modified by it:

let x = 10;

eval("x = 20");

console.log(x); // 10, value modified

Eval has its own lexical environment in the strict mode. So, no one can see the functions and variables, declared in it:

//'use strict' is enabled in runnable examples by default

eval("let x = 10; function fn() {}");

console.log(typeof x); // undefined, no such variable

// function fn is not visible

Be Careful with Eval!

It is essential to note that eval() is quite a dangerous function. That’s why in modern programming the phrase “eval is evil” is so actual. So, using it is a bad practice for a programmer.

In case you run it with a string, which may be impacted by a malicious party, it can lead to malicious code on the user’s device with the permissions of your page or extensions.

Luckily, in modern JavaScript, there is an opportunity to replace it with JavaScript Module or other modern language constructs.

Reactions

Post a Comment

0 Comments

close