What’s the deal with the eval() function in Javascript?

My Blog. Full Stack Software Engineer. Ex-Growth Hacker.

What’s the deal with the eval() function in Javascript?

eval() function javascript, what to use instead

I can across the eval function today when looking for an alternative to a multiple, nested if statement.

This if statement would check what a certain key’s title was and invoke the function which  corresponded to that key name.

We thought about listing this out as key value pairs (with the function as the value) in a new map object. This would require us to store the function as a string. We would therefore need to convert this from a string to a function to call it later. For this the eval function seemed to be perfect…. How wrong we were.

What is the eval() function?

The eval(“given string”) method is one on the global object.

 It is passed a string, for example “if x => {console.log(‘x’)}”, which it then evaluates and calls as JavaScript code.

 You would use it if you want to set up a function but call it later.

Why should it never be used?

  1. It is very dangerous from a security perspective. A third party could pass malicious code to this function which is then executed on a users machine with the privileges of the caller.
  2. It is very inefficient. It creates a separate JS interpreter and executes this function there not with the rest of the code.

 

What did we do instead?

A switch, case statement would be slightly better than an if statement but still messy. Creating an object or array of objects then looping through it would be the best option in terms of cleanness of code and efficiency. This is what we decided to go with due to the huge problems with the eval function.

 

Leave a Reply

Your email address will not be published. Required fields are marked *