# eval

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

{% hint style="success" %}
evaluates script (in the <mark style="color:yellow;">**current**</mark> [**scope**](../..)) 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](../../../concept/env/js-engine/mode/strict-mode/eval-has-its-own-scope-in-strict-mode "mention").:exclamation:
{% endhint %}

{% hint style="info" %}
* <mark style="color:purple;">**eval**</mark> is a [special](../../../grammar/token/id/special "mention").
{% 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**](..). :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&#x26;token=2efbca8f-a3d3-41da-9205-73f6b7b2f65c" alt="" class="gitbook-drawing">
{% endtab %}

{% tab title="👥" %}
* in [strict-mode](../../../concept/env/js-engine/mode/strict-mode "mention"), script in [eval](eval "mention") has its own [..](../.. "mention").
{% endtab %}

{% tab title="💈範例" %}
* 💈範例：&#x20;
  * property [attr](../../../val/obj/prop/attr "mention")
* 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](../../../../master/ref/javascript-the-definitive-guide "mention") ⟩ 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 %}
