For example, suppose we have a string given below:
var myString = "number";
Can you use the string “number” as a variable name?
Now see the example below:
eval("distance = 345"); console.log(distance);
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.
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);
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.