Eval: Executes the code string

The eval function allows the execution of a code string.

The syntax is as follows:

let result = eval(code);
Copy the code

Such as:

let code = 'alert("Hello")';
eval(code); // Hello
Copy the code

The code string may be long, containing newlines, function declarations, variables, and so on.

The result of eval is the result of the last statement.

Such as:

let value = eval('1 + 1');
alert(value); / / 2
Copy the code
let value = eval('let i = 0; ++i');
alert(value); / / 1
Copy the code

The code in EVAL executes in the current lexical environment, so it can access external variables:

let a = 1;

function f() {
  let a = 2;

  eval('alert(a)'); / / 2
}

f();
Copy the code

It can also change external variables:

let x = 5;
eval("x = 10");
alert(x); // 10, the value is changed
Copy the code

In strict mode, eval has its own lexical context. Therefore, functions and variables declared in eval cannot be accessed externally:

// Tip: All runnable examples in this tutorial have the strict mode 'use strict' enabled by default

eval("let x = 5; function f() {}");

alert(typeof x); // undefined (no such variable)
// Function f is also not externally accessible
Copy the code

Without strict mode enabled, Eval has no lexical environment of its own, so we can access variable X and function f externally.

The use of “eval”

Eval is rarely used in modern programming. People often say “Eval is the devil”.

The reason is simple: once upon a time, JavaScript was a very weak language and a lot of things could only be done through eval. But that was ten years ago.

There is little reason to use Eval these days. If someone is using it, this is a good opportunity to replace them with modern language constructs or JavaScript modules.

Note that Eval’s ability to access external variables has side effects.

Code compression tools (tools that compress JS before putting it into production) rename local variables to shorter ones (such as A and B) to make code smaller. This is usually safe, but not when eval is used, because local variables can be accessed by code in EVAL. So the compression tool does not rename all the variables that might be accessed from eval. This results in lower code compression.

Using external local variables in Eval is also considered a bad programming habit because it makes code maintenance more difficult.

There are two ways to avoid such problems altogether.

ifevalThe code does not use external variableswindow.eval(...)Call in the form ofeval:

This way, the code is executed in the global scope:

let x = 1;
{
  let x = 5;
  window.eval('alert(x)'); // 1 (global variable)
}
Copy the code

ifevalThe code needs to access local variables, which we can usenew FunctionalternativeevalAnd pass them as arguments:

let f = new Function('a'.'alert(a)');

f(5); / / 5
Copy the code

We explained the new Function constructor in detail in the “New Function” syntax chapter. New Function creates a Function from a string and is also in global scope. So it can’t access local variables. However, as in the example above, it is much clearer to pass them explicitly as parameters.

conclusion

Calling eval(code) runs the code string and returns the result of the last statement.

  • In modern JavaScript programming, it is rarely used and often not needed.
  • External local variables can be accessed. This is considered a bad programming habit.
  • Be in global scopeevalCode can be usedwindow.eval(code)Substitute.
  • In addition, if your code needs to fetch data from an external scope, usenew FunctionAnd passes the data as an argument to the function.

Homework assignments

Do the questions yourself and then look at the answers.

The Eval – calculator

Importance: ⭐️⭐ ⭐️⭐️

Create a calculator that prompts the user for an arithmetic expression and returns the result of its calculation.

In this case, you don’t need to check that the expression is correct. You just compute and return the result.

The answer:

Reply 11402 in the background of wechat public account “Technology Talk” to get the answer to the assignment.


Modern JavaScript Tutorials: Open source modern JavaScript tutorials from beginner to advanced quality. React provides a JavaScript tutorial for MDN learners.

Read for free online: zh.javascript.info


Search the official wechat account “Technology Talk” and subscribe for more exciting content.