0
votes

I have the following issue:

const value1 = "some value";
var   value2 = "some value";

console.log(window["value1"]); // undefined
console.log(window["value2"]); // some value

I know that const is block scoped and that is the reason I cannot access it through the window object. My question is, is there any way to access a const variable using only a string identifier.

If all I have access to is "value1", how do I get a handle on the actual value1? Is it even possible?

1
I'm not sure If I can use eval for this, but I would rather not use eval.Frank
Yes, you could use eval, and yes you should not do that. Why not simply do console.log(x == "value1" ? value1 : …)? Why do you even need to access local variables by string, why don't you use an appropriate data structure (like a Map or an object)?Bergi
If you must use a string to access a variable like that, why not just use an object? const constants = { value1: "some value" }; Then you can get it using console.log(constants["value1"]).Heretic Monkey
@HereticMonkey, that's exactly what I did. I will use this for the time being. I'm still curious if it's possible, but probably not since it's block scoped. This may have been a hasty question.Frank

1 Answers

0
votes

It appears that, block scope declarations, like let and const, are not added to the global object, meaning you can not access them through a property of window.

See this related question on Stack Overflow: https://stackoverflow.com/a/28776236/10965456

eval should work eval("values1"), as well as the Function constructor new Function("return value1")(), though I'm not sure why this is necessary. If you need to dynamically access certain values, use an array, object, or map instead.