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

213
Views
Converting `eval` statements to functions (implicit return)

I have developed a large number (>1000) strings that are intended to be fed into eval. I am trying to migrate away from using eval, as "eval is evil" and I'm generally trying to make things more secure. However, migrating from eval into a properly defined function is a little tricky, as eval() returns the value of the last expression evaluated. This means that a string that was previously evaled like this:

const stringToEvaluate = "x = 1; x + 1"

is difficult to migrate directly into a function, because the last expression in the statement does not explicitly return anything. With regards to the string above, I might use eval in this way:

const y = eval(stringToEvaluate)
console.log(y) // 2

However, I can't use:

const y = (function safeFunction() {
   x = 1;
   x
})()
console.log(y) // undefined

as safeFunction does not return anything.

Importantly, I am looking for a way to migrate these eval strings without needing to modify each individual string to include return statements in appropriate places. This is because the large number of scripts would make this quite inconvenient. Also, the scripts can be more complicated than this, but this is a nice, minimal example.

Does anyone happen to know of any way to migrate these scripts into functions without needing to manually edit each of them? Also, this is one my first times posting to StackOverflow, so I welcome any feedback about ambiguity in my question! Thanks!

Edit: Apologies for the ambiguity, another example of a "string" to be converted into a script is:

const stringToEvaluate = """
let x; 
if (
    $('.itemToFind').length > 0 &&
    $('.itemToFind').html().trim() != ''
  )
    $('.itemToFind del').html().trim();  <<< eval wraps either this
  else if ($('.price h4.offer-price').length > 0)
    $('.itemToFind').html().trim();      <<< or this
"""

(note that I have included the string across multiple lines to aid readability).

about 4 years ago · Juan Pablo Isaza
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!