View Full Version : Resolved alternatives to the use of the eval function

12-15-2009, 01:49 AM
Hi - I wrote some code that uses the eval function. I am in the process of rewriting the code to improve on it where possible (a learning exercise). I have read that eval is evil because of security concerns and that the eval'd code is not compiled prior to runtime.

I don't think my use of eval presents a security concern. However, I wonder if there is some way to replace the eval function with a more natural technique.

I have done this using eval(); also using a new Function method. I have tried using a window[] method but I can't get that to work.

OK, on the the actual code:

The purpose of the javascript is to count keystrokes.

I have a bunch of global counter variables declared in this fashion:


When the Count function is called I want to update the appropriate counter. Thus: MyLib.Count'+varkeyname+'+=1; Where varkeyname is 'q' or 'w' or 'e' etc.

//MyLib is a global variable namespace.

function Count() {//updates counters
var varkeyname= specialchars(MyLib.KeyName);//identity of the key pressed.
var stra="Count"+varkeyname;// string used to change an html value.

//var strb=eval("MyLib.Count"+varkeyname+"+=1");//original eval function that worked just fine.

var strb='return MyLib.Count'+varkeyname+'+=1';//string to update a counter.

var myfunc= new Function(strb);//Function intended to replace the eval function - this also works just fine.

document.getElementById(stra).value = myfunc();


You can see that I have replaced the eval function with another function - but since this is also not compiled prior to runtime I don't think this is an improvement. I have read about using the window[string] method but I can't get it to work.

This is not a critical issue but I'd appreciate any comments.

Thanks, Jim

Old Pedant
12-15-2009, 02:23 AM
MyLib.Count = [];
MyLib.Count["Q"] = 0;
MyLib.Count["W"] = 0;
function Count()
var varkeyname= specialchars(MyLib.KeyName);

Or initialize it even simpler:

var Count = { "Q": 0, "W": 0, "E": 0, "R": 0, "T": 0, "Y": 0 }

Count["Y"] += 17;
var msg = "";
for ( var c in Count )
msg += c + "::" + Count[c] + "\n";

rnd me
12-15-2009, 03:29 AM
Function() is arguably worse than eval, forget about it...

could be simply


Old Pedant
12-15-2009, 03:52 AM
LOL! Right you are! Trust me to go around the mountain in the other direction.

Well, I suspect mine would *barely* outperform that, but if he had to restructure other code clearly that's a winner.

12-15-2009, 06:51 AM
Excellent replies.

This advances my understanding of syntax. The simpler solution was what I was hoping for right now since I can use it as is; but I may eventually decide to put the counter variables into an array or a list to make the code more compact. Thanks! - Jim Gallagher

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum