Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set a local variable from new function in JavaScript

I have a function with a variable. I need to run code from a string to modify that variable. How would I set a local variable from new Function() or something similar?

function alertNumber() {
  var number = 5;
  var f = new Function("number = 4");
  f();
  console.log("local " + number); //should alert 4
  console.log("window " + window.number); //instead of the local variable, it sets the property to the window
}
alertNumber();

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

With new Function, it’s not possible.

However, unlike eval (which may have access to the local scope), the Function constructor creates functions which execute in the global scope only.

You would need

function alertNumber() {
  var number = 5;
  eval("number = 4");
  console.log("local " + number); //should alert 4
}
alertNumber();

(though having to do this in the first place is quite suspicious – if it were me, I’d consider hard if there were really no alternatives first)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading