0

I want to use eval to calculate the following string with multiple varaibles I have all the variables stored in my object

let myVars = {
    a : 10,
    b : 20,
    c : 30,
}
let str = "a+b+c+10"
// how to evaluate the string ...
so_hell
  • 41
  • 5
  • Can you please share what you've tried so far and what you're having trouble with? – Nick Parsons Mar 21 '22 at 07:55
  • This is not a use-case for `eval`, just use the properties in the object: `myVars.a + myVars.b + myVars.c + 10` – Teemu Mar 21 '22 at 07:56
  • @Teemu OP has an arbitrary string, not a JavaScript expression. – AKX Mar 21 '22 at 07:56
  • I don't know how to do it, and can't find the answer on the internet – so_hell Mar 21 '22 at 07:56
  • `I want to use eval to calculate the following string` What do you mean by this? What is the desired result? – StudioTime Mar 21 '22 at 07:57
  • That string has nothing to do with the given object. – Teemu Mar 21 '22 at 07:57
  • @Teemu , this is just an example the string is random all the time.. – so_hell Mar 21 '22 at 07:57
  • @StudioTime, the strings are random all the time and I have values stored in an object , each time I want to calculate the value of string , in this case str = "a+b+c+10" therefore the result will be 70 – so_hell Mar 21 '22 at 07:58
  • 1
    What is the use-case? [eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) is not usually the best practice. – Teemu Mar 21 '22 at 07:59
  • @Teemu do you know how to do it the best way?? – so_hell Mar 21 '22 at 07:59
  • Maybe, but we need to know the exact use-case. Where is the string coming from? How is the object created, why are you needing this? – Teemu Mar 21 '22 at 08:00

5 Answers5

1

You could replace the (unknown) variables and use eval (cave!) for getting a result.

let
    values = { a: 10, b: 20, c: 30 },
    str = "a+b+c+10";

str = str.replace(/[a-z0-9_]+/g, s => values[s] ?? s);

console.log(eval(str));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

I'm not sure if I understood your question, but I will try my best to answer.

The eval() method will automatically get the variables from the global context. If you want to get the result, just save the result from the eval() function.

// Object destructuring for easier readability
let { a, b, c } = {
  a : 10,
  b : 20,
  c : 30,
}
let str = "a + b + c + 10";

const total = eval(str);
console.log(total); // Should be: 70

The code above will return the result from the mathematical operation.

However, you should never use eval(), as it can run any code arbitrarily.

Arnav Thorat
  • 3,078
  • 3
  • 8
  • 33
0

You have to mention that a+b+c... are for the myVars object so you have different ways:

let myVars = {
    a : 10,
    b : 20,
    c : 30,
}
let str = "myVars.a+myVars.b+myVars.c+10"
console.log(eval(str))

Although I don't suggest this way to you because here we can use that without eval so that will be easier.

Another way is to use Regex:

let myVars = {
    a : 10,
    b : 20,
    c : 30,
}
let str = "a+b+c+10"
const arrayName="myVars"
str=str.replace(/([a-z]+)/gi,arrayName+".$1")
console.log(eval(str))

Here you add the object name behind the variables dynamically with Regex.

Or simply you can do what you want without eval (If you want):

let myVars = {
    a : 10,
    b : 20,
    c : 30,
}

let sum=Object.values(myVars).reduce((partialSum, a) => partialSum + a, 0) + 10;
console.log(sum)
Atena Dadkhah
  • 623
  • 1
  • 5
  • 19
0

You can use mathjs library instead.

First download the library:

npm install mathjs

Import evaluate(), then simply use evaluate(expression, scope) like this:

let myVars = {
  a : 10,
  b : 20,
  c : 30,
}
let str = "a+b+c+10"
console.log(evaluate(str, myVars)) # Prints 70

Check the documentation for more examples: mathjs

-1

While remembering that Eval is Evil since it allows for arbitrary code execution, you can use the with block here to change the eval statement's global namespace:

let myVars = {
  a: 10,
  b: 20,
  c: 30,
};
let str = "a+b+c+10";
let result = null;
with (myVars) {
  result = eval(str);
}
console.log(result); // logs 70

Again, I do not recommend using eval.

AKX
  • 152,115
  • 15
  • 115
  • 172
  • `eval` is not evil automatically, ([see also Shog9's answer](https://stackoverflow.com/a/197823/1169519)). There's nothing `eval` can do what DevTools couldn't. The problems start if you'll send the eval'd (user input) content to your server, and then put it on pages anybody can visit. – Teemu Mar 21 '22 at 08:22
  • 1
    the `with` statement was deprecated and not recommended already 10 years ago so your code doubles down on unrecommended code – mplungjan Mar 21 '22 at 09:35
  • @mplungjan Where did you find the information that it's deprecated? Sure, it's not recommended for multiple reasons, as the MDN page says, but there are no indications of deprecation. – AKX Mar 21 '22 at 10:08
  • Ok, it is in ALL INTENTS AND PURPOSES deprecated https://stackoverflow.com/questions/48810592/is-the-javascript-keyword-with-really-deprecated – mplungjan Mar 21 '22 at 10:14
  • The first thing MDN says on the `with` statement documentation is that it shouldn't be used! [See it here.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with) – Arnav Thorat Mar 26 '22 at 22:55