> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/scope/global/object/eval.md).

# eval

[JS](/web/js.md) ⟩ [concepts](/web/browser/concepts.md) ⟩ [scope](/web/js/scope.md) ⟩ [global](/web/js/scope/global.md) ⟩ [global object](/web/js/scope/global/object.md) ⟩ eval()

{% hint style="success" %}
evaluates script (in the <mark style="color:yellow;">**current**</mark> [**scope**](/web/js/scope.md)) and returns its completion value.

:octagonal\_sign: [Never use eval()](https://developer.mozilla.org/en-US/docs/Glossary/property#never_use_eval!):exclamation:
{% endhint %}

{% tabs %}
{% tab title="⭐️" %}
{% hint style="warning" %}
[eval has its own scope in strict mode](/web/js/concept/env/js-engine/mode/strict-mode/eval-has-its-own-scope-in-strict-mode.md).:exclamation:
{% endhint %}

{% hint style="info" %}

* <mark style="color:purple;">**eval**</mark> is a [special identifier](/web/js/grammar/token/id/special.md).
  {% endhint %}

{% hint style="warning" %}
Functions created with the [**Function**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function#difference_between_function_constructor_and_function_declaration) <mark style="color:yellow;">**constructor**</mark> <mark style="color:red;">**always**</mark> are created in the [**global scope**](/web/js/scope/global.md). :point\_right: [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function#difference_between_function_constructor_and_function_declaration)
{% endhint %}
{% endtab %}

{% tab title="🗺️" %} <img src="https://2527454625-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MfvEFZnSBhKT6fJmus0%2Fuploads%2FgJHR84kHTMOnbZ8MLJJz%2Feval.svg?alt=media&amp;token=2efbca8f-a3d3-41da-9205-73f6b7b2f65c" alt="" class="gitbook-drawing">
{% endtab %}

{% tab title="👥" %}

* in [strict mode](/web/js/concept/env/js-engine/mode/strict-mode.md), script in [eval](/web/js/scope/global/object/eval.md) has its own [scope](/web/js/scope.md).
  {% endtab %}

{% tab title="💈範例" %}

* 💈範例：&#x20;
  * property [attribute](/web/js/val/obj/prop/attr.md)
* replit： [eval](https://replit.com/@pegasusroe/eval#index.js)

```javascript
// 'use strict';                // ⭐ toggle sloppy/strict mode
const { log } = console;
const { tryEval } = require('./helpers/ErrorHandling.js');

// ⭐ eval code in a function
function f() {
    
    let x = 1;

    // ⭐ access local variables
    log(eval('x'));                        // 1
    eval('x = 2');
    log(eval('x'));                        // 2
    
    // ⭐ call eval in another function
    let r1 = tryEval(`x = 3`);
    log(r1);                               // { value: 3 }
    log(eval('x'));                        // 2 (`x` not affected❗)

    // ⭐ declare new variables
    eval(`var y = 3`);        // ⭐ in strict mode, var `y` is local to eval❗
    log(`y = ${y}`);          // 'y = 3' (in sloppy mode, it's OK)
    
    eval(`let z = 500`);      // ⭐ "let/const" is ALWALS local to eval❗
    // log(`z = ${z}`);       // ⛔ ReferenceError
    // ReferenceError: z is not defined

    // ⭐ declare function (can access variables in the current scope)
    eval(`function g() { return x += 10 }`);
    log(`g() = ${g()}`);     // 12
    log(x);                  // 12
}

// execute it
f();

// log
[
    tryEval(`300`),    // { value: 300 }
    tryEval(`+40n`),   // { error: TypeError }
    
].forEach(x => log(x));
```

📁 ErrorHandling.js

```javascript
// ⭐ try to eval an `exprStr` (don't include any variables, literals only!)
// returns: result (object)
//   • access `result.value` (any) if successful,
//   • access `result.error` (Error object) otherwise.
function tryEval(exprStr) {

    let result = {};

    try { result.value = eval(exprStr); }
    catch (err) { result.error = err; }

    return result;
}


// ⭐ try to transform a value
// returns:
//   • transformed result (object)
//     (access result.value if successful, result.error otherwise)
function tryTransform(value, transform) {

    let result = {};

    try { result.value = transform(value); }
    catch (err) { result.error = err; }

    return result;
}

// ⭐ get the result of transforming a value
// returns:
//   • transformed value (any)
//   • error type name (string)
function getResult(x, transform) {
    let result = tryTransform(x, transform);
    return result.error ? result.error.name : result.value;
}

// export
module.exports = { tryTransform, getResult, tryEval };
```

{% endtab %}

{% tab title="📗" %}

* [ ] [JavaScript: The Definitive Guide](/web/master/ref/javascript-the-definitive-guide.md) ⟩ 4.12 Evaluation Expressions (eval)
* [ ] Eloquent JS ⟩ [Evaluating Data as Code](https://eloquentjavascript.net/10_modules.html#h_oeOkEDaadU)
  {% endtab %}

{% tab title="📘" %}

* [eval()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval)
* [Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) ⟩ [Difference between Function constructor and function declaration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function#difference_between_function_constructor_and_function_declaration)&#x20;
  {% endtab %}
  {% endtabs %}
