Convert a string into a variable name in JavaScript

Did you ever think to use a JavaScript string as a variable name?

For example, suppose we have a string given below:

var myString = "number";

Can you use the string “number” as a variable name?

Well, it is possible, and here in this simple tutorial, I am going to show you how to convert any string into a variable in JavaScript.

To do this task, we will use the JavaScript eval() function. Well, this is the function that will play the main role to create variable name from our string.

Now see the example below:

eval("distance = 345");
console.log(distance);

If we run these two lines of JavaScript code, then it will show the result given below:

345

Now why it’s happening? This is because the distance string is now a variable when we use it in the place of the variable.

So what actually the eval() function did?

To understand this first let me tell you what is the functionality of the eval() function.

The eval() function is able to evaluate or executes an argument that is passed inside it.

If the argument is an expression, this function will evaluate the expression and the argument is one or more JavaScript statements, eval() executes the statements.

In our example you can think like this – The string we pass inside the eval() function is actually treated as a JavaScript code.

Now let’s see another example:

Now below is another example where we assign a string in a variable which we already did it and then convert that string into a variable name:

var myString = "number";
eval(myString +" = 9");
console.log(number);

In this example, the eval() function is doing the same task. Now running the above JavaScript code will give the result 9 which proves that we were able to create a variable name with our string.

So you can see that we are actually performing our task just within two lines of code. Or if you notice carefully then it is actually done within just one line of code as the main trick is in the line where we are using the eval() function.

I hope, you like this trick and it will be useful in your task.

Leave a Reply