How to execute a valid code string in JavaScript?

January 30, 2021 - 1 min read

To execute a code string, you can use the eval() global function in JavaScript.

Consider a string which itself is a valid piece of JavaScript code like this,

// javascript code as string
const codeStr = `
if(12 > 10){
    console.log('12 is greater')
}`;

As you can see the above string is an actual valid piece of if statement in JavaScript.

To run this string, let's use the global eval() function in JavaScript.

// javascript code as string
const codeStr = `
if(12 > 10){
    console.log('12 is greater')
}`;

// run string using eval() function
eval(codeStr); // 12 is greater
  • The code string will be executed using the eval() function.
  • This is useful when having an application of some kind where you can receive the JavaScript code as the string and then needs to be executed.
  • This can also make serious problems to the application if you are not careful enough using the eval() function and it is not at all recommended t use it in a real-life application. ✨

See this example live in JSBin.

Feel free to share if you found this useful 😃.