Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
javascript eval with multiple variables

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 ...
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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));

about 4 years ago · Juan Pablo Isaza Report

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.

about 4 years ago · Juan Pablo Isaza Report

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!