Explain Codes LogoExplain Codes Logo

Execute JavaScript code stored as a string

javascript
eval-security
javascript-alternatives
vm-module
Alex KataevbyAlex Kataev·Dec 20, 2024
TLDR

Execute a string of JavaScript code swiftly using eval(). Simply write:

eval("alert('Executed!');"); // like a spell being cast!

This pops an alert saying "Executed!". Use eval() with caution. Welcome to the wild west of JavaScript; eval() is fast but can run any script passed to it.

Understand eval() security risks

eval() has a reputation. Security risks are real. You wouldn't set your house on fire to cook dinner, would you?

The importance of sanitizing the JavaScript string before using eval() cannot be overstated. Injection attacks are no laughing matter.

Alternate ways to execute JavaScript strings

"Keep your friends close and your alternatives to eval() closer."

Utilizing the Function constructor

No, we're not building robots, but the Function Constructor here:

var func = new Function("return 'Hello World!';"); func(); // Hello World!

Like a private detective, it avoids using the outer scope.

Node.js vm module to the rescue

The vm Module in Node.js provides a separate execution context for your JavaScript string.

const vm = require('vm'); const script = new vm.Script("console.log('Hello from VM');"); script.runInThisContext(); // Hello from VM

Safe execution with vm2 in Node.js

"As safe as a kitten in a basket", vm2 provides a sandboxed environment for running untrusted code in Node.js. It's like playing with scissors but without the risk of getting hurt.

const { VM } = require('vm2'); const vm = new VM(); vm.run("console.log('Sandboxed execution');"); // Sandboxed execution

To avoid becoming an episode in a future hacking documentary, remember to check for recent security updates and deprecated APIs in vm2.

Executing scripts with jQuery

Sometimes, old is gold. The good old <script> tags can also execute your JavaScript string with the help of jQuery.

var code = "$('body').append('<p>Hello from jQuery!</p>');"; $('<script>').attr('type', 'text/javascript').text(code).appendTo('body'); // Hello from jQuery!

Visualization

Imagine your JavaScript code as a rolled-up map (📜) in an explorer's bag:

📜: "alert('Hello, World!');"

Using eval() is like plotting the coordinates on the map:

eval("alert('Hello, World!');");

Bang! Just like that. The location revealed, an alert pops up!

Before: [📜] After: [💬 'Hello, World!']

Comprehensive guide for alternatives to eval()

Here's a deep dive into more secure, efficient (and less hair-pulling) alternatives to eval():

In-depth with the Function constructor

This constructor is no mere mortal:

  • Creates functions dynamically, a bodyguard compared to eval()
  • Accesses only global variables, keeping your local scope as intact as a museum artifact

Safe execution with Node.js vm

The vm module is like a Swiss army knife:

  • Executes third-party scripts without breaking a sweat
  • Provides a controlled environment, guarding against unwanted side effects

Using jQuery for script execution

jQuery, the reliable workhorse:

  • Create a script element
  • Set the text content to your JavaScript string
  • Append the script to a DOM element for instant action