Eval() function not accepting the values of the imported variable

Hi,
I am having two .js files. From one js file, I am passing a variable as string . In second js, I am using eval() function to convert the string to a variable name. When the converted name in second js is declared in the second js then the value is getting right. But if the converted name in second js is imported in second js from some other js , then that is not working. Why?

Hi,

I think you can not do this.
What are you trying to do?

Actually, I am importing some constants from a js file and I just pass the variable name as string in a json . So, Now I need to convert that string to variable . For this, I am using eval() function

Sorry, I don’t quite get it.
So you import some value from another file.
What is this value? a string?

Note if you want the data back from JSON, then you can do JSON.parse().
If you want to convert JSON data to string than use JSON.stringify().
Not eval.

No @padunk . I am not saying that. Have you seen about eval() function ?

Why not try something else

@padunk they can sort of do this.

@krjk333 can you please provide an example of the code? It’s very difficult to tell from your descriptions what exactly you’re attempting. Can you also explain why you’re trying to do this? What you’re trying to do is sort of possible in a sense, but even if you’re doing that it’s almost always a dreadful idea. It’s vanishingly unlikely that you actually need to do some eval hack that kinda sorta creates variables.

1 Like

Hi @DanCouper can you show me the trick?
I know it’s not a best way to do that, I’m just curious.
I try couple of tricks and I couldn’t do that

Thanks for your reply @DanCouper and @padunk and @larva . Please see the example below. I don’t know, how it is working here and why it is not working in my actual project.

@padunk

var varName = "variableName"
var varValue = 1
eval(varName + "=" + varValue)
console.log(variableName) // 1

You can’t just magically create variables @krjk333, you can only evaluate expressions, so if you have a string like "var foo = 1", then eval will evaluate that as JS code. If you have a string, like "foo", and you eval it, it’s just a string, that’s all.

I’m not sure what you mean by it working, because at the minute it doesn’t seem to do anything useful even if it could work. Why are you not just using an object? That’s the normal answer to someone asking how to dynamically create variables. I’m sure there is some use that can be made of dynamically created JS code via eval, but you really need to know what you’re doing, there seems to be no reason at all to attempt to dynamically create variables in the code you’ve posted.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.