Alternative option for new Function String to real javascript

Viewed 1815

How to convert string to real javascript object if we don't use new Function

var sum = new Function('a', 'b', 'return a + b')
console.log(sum(2, 6))

So 'a', 'b', 'return a + b' is generated by another javascript snippet and everything is string format. eslint suggests do not use Function constrctor The Function constructor is eval. (no-new-func) If not using Function constrctor is there another option can do the same job? Thanks

1 Answers

...is there another option can do the same job?

There is (eval), but it's even worse than new Function.

Creating a function from a string is fundamentally insecure. If you can absolutely trust that the string is safe and you have no choice but to convert a string into a function, then new Function is the right tool.

But instead, the better option is to avoid having to create a function from a string.


Re the "absolutely trust" bit, here's an example of what not to do: Don't allow Bob to provide the string, and then use that string as code in Alice's environment (her browser, or worse in an unrestricted environment like Node.js). Doing so exposes Alice to a security risk. (Obviously, on sites like SO, if Alice is a programmer and can read the code before running it, that's different. ;-) )

Related