I need to declare some variables. If I pass the variable name to a function it should declare all variable. (variable might be using for instantiating an object.)
Asked
Active
Viewed 159 times
-2
-
1eval is evil. never use – Red Baron Jun 24 '20 at 07:02
-
3do you have a use case for it? – Nina Scholz Jun 24 '20 at 07:03
-
Don't use it. The docs literally say never use it. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Never_use_eval! – JMadelaine Jun 24 '20 at 07:16
-
1Why do you need to make the variable name dynamic? Why is the variable name even important? When your code gets modified, the variable name is changed to a single letter anyway. – JMadelaine Jun 24 '20 at 07:17
-
"*I need to declare some variables.*" then declare them. "*If I pass the variable name to a function it should declare all variable.*" pass an object instead. Otherwise the function is completely coupled with the way it's called. If you have `function myFunction(varName) { /* dynamically create a variable from varName */ console.log(foo)}` and expect it to work only for `myFunction("foo")` then the dynamic creation is completely useless. You cannot call `myFunction("bar")` because it would lead to an error. The *only* variable names allowed are the ones you expect. Why not just declare them? – VLAZ Jun 24 '20 at 07:50
-
[“Variable” variables in Javascript?](https://stackoverflow.com/q/5187530) – VLAZ Jun 24 '20 at 07:52
2 Answers
3
Short answer — you should not.
Long answer.
It is a bad way, because eval is a really dangerous thing. You can read about problems here — https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval.
Also, it can produce bad design of your application. Try to replace dynamic variable name with other solution. E.g., object property.
Let's look at the code-example:
function createObject(fieldName, value) {
return {
[fieldName]: value
}
}
In this piece of code, we don't use eval, but have object with dynamic key.

Igor Kamyshev
- 149
- 1
- 9
1
you can declare a variable dynamically without eval by using square brackets:
var variableName = 'someVariable';
someObject[variableName] = 'some value';

andriusain
- 1,211
- 10
- 18
-
-
true, but isn't a global variable a property of window object anyways? The example may be practically useful nonetheless. – andriusain Jun 24 '20 at 08:13
-
A global `var` declared variable is added to the global object, yes, however `let` and `const` variables are not added to the global object, they only exist in the global space. So, mixing up the concepts of properties and variables can be problematic as they aren't the same and don't always work the same way. – VLAZ Jun 24 '20 at 08:18