JavaScript eval() Method Alternative

Shiv Yadav Oct 12, 2023
JavaScript eval() Method Alternative

The eval() method is used to evaluate or implement an argument. If the argument is an assertion, the expression is evaluated by eval(), and if the argument contains one or more JavaScript statements, eval() will execute them.

With eval(), malicious code can run inside your application without your permission, and third-party code can see the scope of your application, potentially leading to an attack.

Use Alternative to eval() Method in JavaScript

JavaScript is a very flexible language. There are very few situations in which eval() is the correct answer to any given question, and it is certainly not required here.

For example, if s and k variables are part of an object, you can use string subscripts to access them. As a result, you can use a variable for the subscript and thus dynamically reference any element in newobj.

Code:

var newobj = {s: 20, k: 30};
var value1 = 's';
var value2 = 'k';
alert(newobj[value1] + newobj[value2]);

Run Code

Output:

javascript eval alternative

There’s no need to use the eval() method. You can construct the value strings in any way you want, giving you nearly infinite flexibility.

If the s and k variables are global, you can use this technique because JS global is children of the window object in the browser.

Specifically, your global variable could be accessed via window.s or window['s'], with the latter allowing you to perform the same dynamicProperty trick described above.

Author: Shiv Yadav
Shiv Yadav avatar Shiv Yadav avatar

Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.

LinkedIn

Related Article - JavaScript Method