Home » JavaScript » Javascript Eval Example

About Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.

Javascript Eval Example

The eval() function is one of the most discussed by JavaScript developers, most of them call it “evil” (such as Douglas Crockford), who coined the saying “eval() is evil”. But what most programmers fail to see is it’s potential when used properly. Take a look!
 
 
 
 
 
 
 
 

What is eval()?

eval() is a function that takes a string that contains valid Javascript code as a parameter, and executes it.

It’s syntax is like this:

eval(string);

Technically, it is used like in the code snippet below, but that doesn’t mean it’s the best way to use it, if you don’t want to be labeled “as evil as eval”:

var firstVar = 3;
var secondVar = 5;
var sum;

sum = eval(firstVar + secondVar);

// output= 15

So, I guess that now you’re asking yourself why were you shown how eval() is used and warned against it all in the same breath. There are quite a lot of reasons for that…

Why the backlash?

Firstly, this function is misused quite a lot, resulting in slower loading times, cross-site scripting (XSS) attacks and more difficult debugging.

Most of the time, this function is used as a gate to attack and steal valuable data from the application it is used in by hackers, so that’s why a lot of programmers are putting together different and efficient ways to evaluate an expression, just to put aside eval().

And they’ve managed to do so, in this way:

eval('document.' + id + '.style.color = "blue"');

document.getElementById(id).style.color = 'blue';

document[id].style.color = 'blue';

Essentially, instead of using the dot-name access to a variable, you can use the square brackets, and eliminate the need to use eval for this.

Or even better, to get your element by its id and style it however you want.

However there are many cases when it’s not only possible to use eval(), but also the best approach to the problem. these cases include:

  • Code caching
  • Evaluating code returned from the server
  • Deferred execution

So let’s see each of these cases separately.

Code Caching

Let’s suppose you have this piece of code and want to re-execute it in a later time:

 var str = "",
     i = 0;
     for (; i<1000; i += 1) {
          str += "a";
     }

The code snippet basically creates an empty string and attaches the “a” string to the one we already have, repeating the action a thousand times.

To evaluate this code you might do this:

var strCode = 'var str="",i=0;for(;i<1000;i+=1){str+="a";}';

eval(strCode).reExecute();

We have turned the code into a string, evaluated it, and then re-executed it.

In this case it would be better if we proceeded like below:

var strCode = 'var str="",i=0;for(;i<1000;i+=1){str+="a";}';

var evalStr = (new Function(strCode))();

var evaled = eval(evalStr);

evaled.reExecute();

Which means that after turning the code we want to evaluate into a string, we have turned it into a function, and then evaluated it. Lastly we have re-executed it.

Some people argue that new Function() should officially replace eval(), though if you would perform speed tests you see that eval() has significantly better performance.

Evaluating code returned from the server

If you don’t already know of XMLHttpRequest, it’s only a component of the set of tools popularly known as AJAX. It makes a call back to the server from Javascript without refreshing the whole page.

It is good programming practice that the code returned is passed to eval() for evaluation. Below is a simple example:

function evalRequest(url) {

    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {

        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            eval(xmlhttp.responseText);
        }

    }

    xmlhttp.open("GET", url, true);
    xmlhttp.send(null);
}

Essentially, we have taken a URL to a Javascript code, and then loaded and executed that code using XMLHttpRequest and eval().

Deferred execution

In some cases, to shorten the loading time of a website, you can use deferred execution of Javascript, which means that the scripts are only executed after page load.

Even though this method is used to improve the rendering speed of the sites, it is considered high risk, and you must very carefully evaluate your code before rendering it.

Due to the many problems it brings, it is said that this method will be no longer available in the near future, which is why we’re not giving a concrete example of how eval() is used together with it.

Download the source code

This was an example of eval in Javascript.

Download
You can download the full source code of this example here: Eval

Do you want to know how to develop your skillset to become a Web Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. Building web apps with Node.js

2. HTML5 Programming Cookbook

3. CSS Programming Cookbook

4. AngularJS Programming Cookbook

5. jQuery Programming Cookbook

6. Bootstrap Programming Cookbook

 

and many more ....

 

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
manikan
manikan
5 years ago

I need all books

Eleftheria Drosopoulou
Editor
Reply to  manikan

Hello Manikan,
You need to join our newsletter here: http://eepurl.com/6iVnH
After you enter a VALID email address, you will need to verify your subscription.
A verification email will be sent to you and after you successfully verify your email,
you will get a final welcome email which will contain the links to download the ebooks!