Executing a String With Eval in JavaScript

- 1 minute read

In JavaScript, eval can be used to execute a given string as code:

eval(`console.log("Hello, world!");`);

The above snippet prints “Hello, world!” to the console.

Keep in mind that when using eval, tge scope is local and strict mode is pre-enabled.

One way to excute multi-line code with eval is to separate lines with \n:

eval(`console.log("Hello, world!");\nconsole.log("Hello again, world!");`);

The above snippet prints “Hello, world!” to the console and prints “Hello again, world!” on a new line.

Link to this section Conclusion

That’s all - just remember to be very careful with what strings can be passed to eval, and always sanitize them to prevent malicious or otherwise unwanted code from executing.