Dynamic variable names in Javascript

Want to play with a variable who’s name you don’t (yet) know at runtime? So did I. Here’s how:

var sheep = "dynamicVariableName";
eval("var " + sheep + " = 'beehh'");

alert(dynamicVariableName);

Result: Shows alert windows with text “beehh”.

You can also do the same with arrays:

var sheep= "dynamicVariableName";
eval("var " + sheep + "= new Array();");

Speed? Eval is VERY fast.

Security considerations? Think twice before passing user submitted code to eval. Use some form of string escaping if you do.

This entry was posted in Code, JS, Programming, Tutorials. Bookmark the permalink.

2 Responses to Dynamic variable names in Javascript

  1. Mick says:

    Thank you for clear explanation!

  2. Chris Adams says:

    Thanks this was perfect. I used it to set multiple counters dynamically:
    var counterName = modelName + “Counter”;
    eval(“if (typeof ” + counterName + ” != ‘number’){ ” + counterName + ” = 1;}”);

    then
    eval(counterName + “++”);
    to render.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>