eval function in javascript

This function is a classic in the language, which is rarely used but contains a lot of power.

It is an important resource for some Javascript applications where you need to programmatically generate code and then execute it with the javascript interpreter. As I said, it is not very common, but if you need to build and execute code dynamically, it is the only solution you have.

Also, by the way, its power means that it is also sometimes used in attacks, potentially being used to obfuscate potentially malicious code, so it is not considered a very secure function. In addition and as a consequence of this, if we are not especially careful when using it, it is easy for us to introduce security holes into applications ourselves.

Its use is very simple, but it may be a little more complex to understand in which cases to use it because its application is sometimes a bit subtle.

With current knowledge we can’t make a very complicated example, but at least we can see the function running. We are going to use it in a slightly strange and quite useless statement, but if we can understand it we will also be able to understand the eval function.

var myText = “3 + 5” eval(“document.write(” + myText +”)”)

First we create a variable with a text, in the next line we use the eval function and as a parameter we pass a javascript instruction to write it on the screen. If we concatenate the strings inside the parentheses of the eval function we get this.

document.write(3 + 5)

The eval function executes the statement that is passed to it as a parameter, so it will execute this statement, which will result in an 8 being written to the web page. First, the sum between parentheses is solved, with which we obtain 8 and then the instruction to write to the screen is executed.

Loading Facebook Comments ...
Loading Disqus Comments ...