Dynamic variable wasn’t new for me but creating variable names on the fly was, I knew it is possible but never tried or had a need. But like always today I had to.

Scenario : It was react native application where the number of inputs I had to manage depends on the users choice, which means dynamic fields. I managed the fields using a loop and named them with loop key. In the web you can just process dynamic forms with square brackets [] to field name it was not the case with react-native. So I had to attach a different name to each input.

That was an easy part, now it’s time to parse them. To assigning name was straight forward but it’s not the case with parsing, here I had to make a variable with key attached to it in order to access the field.

Solution is to use eval. It’s a function which evaluates a string as though it were an expression and returns a result in languages that support it, in others it executes multiple lines of code as though they had been included instead of the line including the eval. Javascript belong to first part so we are good to go.

Here how you do it.

var alphabet0 = 'A',
    alphabet1 = 'B',
    alphabet2 = 'C';

var no_of_alphabet = 3; 
for ( var i=0; i

In JavaScript, eval is something of a hybrid between an expression evaluator and a statement executor. If a statement is left in the argument it will executor it. I haven't tried this let me know if you have.