🔸eval
Last updated
Last updated
JS ⟩ concepts ⟩ scope ⟩ global ⟩ global object ⟩ eval()
evaluates script (in the current scope) and returns its completion value.
eval is a special identifier.
Functions created with the Function constructor always are created in the global scope. 👉 MDN
in strict mode, script in eval has its own scope.
// '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
// ⭐ 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 };