Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative option for new Function String to real javascript [duplicate]

Tags:

javascript

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

like image 678
olo Avatar asked Aug 01 '26 09:08

olo


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. ;-) )

like image 174
2 revsT.J. Crowder Avatar answered Aug 02 '26 23:08

2 revsT.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!