๐ธeval
Last updated
Last updated
JS โฉ concepts โฉ scope โฉ global โฉ global object โฉ eval()
evaluates script (in the current scope) and returns its completion value.
๐ Never use eval()โ
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 };