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

189
Views
How to remove new Function with Anonymous function in javascript

I am trying to replace eval/new Function with corresponding anonymous function.

Existing Code -

var y = 2
var fn = new Function("return" +y)
console.log(fn)

When i print fn output is

ƒ anonymous(
) {
return2
}

Refactored code which i am writing -

var y = 2
var fn1 = function()  {return y}
console.log(fn1)

But fn1 in this case is

ƒ ()  {return y}

Any pointers how can i get the same output as fn ƒ anonymous() {return2} using my own anonymous function.

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

0

You can't (at least not without using another version of eval).

You can get the same effect (i.e. not having a mutable y) by using a closure.

var y = 2
var fn1 = function(closure_y) {
  return function() {
    return closure_y;
  }
}(y)
y = 3;
console.log(fn1())

If your code depends on a function stringifying itself in a particular way, then you should probably rewrite the code so it no longer depends on that.

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!