Generate Variables from string in Javascript

Generate variables in JavaScript from strings using eval. It's a function which evaluates a string as though it were an expression.


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<no_of_alphabet; i++ ) {
     console.log( eval(" alphabet"+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.


Wow ! you have someting to tell us. That's great! Please keep in mind that comments are moderated, we employ rel="nofollow" for links, avoid using a spammy word or a domain in name field, it might end up as a Spam. Thanks for reading.

Last 5 Articles

All Articles >

  1. Mitigating Risks In Custom Software Development

  2. Container Security to Secure Microservices

  3. Strategic Messaging

  4. URL Shortener in Django

  5. MySQL as Database Option


News Letter

Subscribe to our email newsletter for useful tips and valuable resources, sent out every new article release.