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

233
Views
Convert function to string and back in javascript

// FYI same thing happens when using a full syntax
const a = () => {
  return "hello world"
}
const aString = a.toString()
const b = new Function(aString)
console.log(b());  // undefined

So b is a closure of a and I could not find an option to prevent the wrapping. Anyone knows how to get back the function without a closure?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

new Function expects a function body as argument, as stated on mdn:

A string containing the JavaScript statements comprising the function definition.

The parameters of the function are not included: they can be passed as separate arguments.

There are at least two ways to make this work:

  1. You could use eval (but in your edit to the question you write this is not possible for your case -- see alternative):

const a = () => {
  return "hello world"
}
const aString = a.toString()
const b = eval(aString)
console.log(b());  // "hello world"

Disclaimer: when the stringified function is not fully under your control, it has similar code injection dangers as new Function

  1. To only use new Function, add return and execute it -- this unwraps the wrapper:

const a = () => {
  return "hello world"
}
const aString = a.toString()
const b = new Function("return " + aString)();
console.log(b());  // "hello world"

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!