eval
is often considered unsafe because it will run any code it takes as an input on the client's device with full privileges of the caller, regardless of whether that code is malicious or not.
If there is a possibility that the string eval
runs could have been affected by a malicious third party, then it is dangerous, as it will have all the permissions your user has granted the webpage.
For example, evil user X might have written a script which your app innocently served to user Y's browser, where it is run with eval
.
In your case, however, since you are not serving data from one user to another, there is no possibility that the string could have been affected by a third party, and it is perfectly fine to use eval
. See this question. Nevertheless, eval is relatively inefficient compared to the alternative Function
. Function, although still unsafe, is more secure, but we have already established that this type of vulnerability does not apply to your use case. More important is the fact that (at least according to the MDN docs), Function
is more efficient. Just do: var result = Function("return" + newArr)();
.
Your client will still be able to write silly things like while(true){console.log("infinite loop")}
, but they could have done this through the console anyway, and it won't affect anyone else. In conclusion, eval
and similar functions are often blindly condemned as "unsafe", but this is only true in certain contexts.