Sometimes, we have a JavaScript string with code in it that we want to run.
In this article, we’ll look at how to execute JavaScript code stored in a string.
Create a New Function with the Function Constructor
We can create a new function from our JavaScript code string with the Function
constructor.
For instance, we can write:
const code = "alert('Hello World'); let x = 100";
const F = new Function(code);
F();
to create the code string and store it into the code
variable.
Then we pass code
into the Function
constructor to create a function from it.
And then we call F
to run the function.
Use the setTimeout Function
We can also pass in the JavaScript code string into the setTimeout
function to run the code string.
To do this, we write:
const code = "alert('Hello World'); let x = 100";
setTimeout(code, 1);
We pass code
as the first argument of the setTimeout
function to run it.
The 2nd argument is the delay in milliseconds before running the function.
Don’t Use the eval Function
We shouldn’t use the eval
function to run code from a string.
This is because anyone can easily inject code into it, which is a big security risk.
Also, it creates its own scope, which means it may do things we don’t expect.
So we shouldn’t write code like:
const code = "alert('Hello World'); let x = 100";
eval(code)
in our JavaScript code.
Conclusion
We can run JavaScript code that’s stored in a string with JavaScript by creating a function from it with the Function
constructor or pass it into the setTimeout
function.