Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Liam Maclachlan
Liam Maclachlan
22,805 Points

How do you convert a string to a variable name?

Hi all,

I am playing around with a few things at the moment but on my 'to figure out' list, I can't find an answer to passing a variable from an input field, and then convert it to a format that will allow me to dynamically create a variable name.

I imagine interpolation will be needed to make this work, if it is possible.

Any ideas? Here is some pseudo code that may help clear things up

function String_to_class(variableName) {
       // code here to convert string?
      ConvertedName = formatConversion(variableName)

      // Use newly formatted string as variable name
      var ConvertedName = 'Here is some text'
}

1 Answer

Timothy Wright-Bodine
Timothy Wright-Bodine
9,670 Points

If I'm understanding the question correctly, you could use eval() to do something like this:

eval("var " + prompt("give me a variable name to assign a value of 5 to") + "=5");

I might be missing the essence of what you're asking though. Apologies if so.

Liam Maclachlan
Liam Maclachlan
22,805 Points

Hey man. I think that is pretty much what I am looking for. I'll try it in my code and get back to you :)

Liam Maclachlan
Liam Maclachlan
22,805 Points

Hmm.. nope. This is my code that is not working. Any ideas? =/

    function createPerson(theVar, name, gender, age) {
        eval("var " + theVar + "= new Person()")
        eval( theVar + ".details('" + name + "','" + gender + "','" + age + "')")
    } 

    createPerson('Liam', 'Liam', 'Male', 26)

EDIT:

Don't worry. Got it :)

    function newPerson(name, gender, age) {
        eval("var " + name + "= new Person()");
        eval(name + ".details(" + name + ", '" + gender +  "', " +  age + ")")
    }

Thanks man

Well... It worked last night. Still Best answer just don't know how I broke I 0_o