0

When i do this in JS:

const myConst = "something";

outside any function, how can I access myConst by its name ?

From what I have understood so far is, that myConst ends up in the "Declarative Environment Record", but i don't know how to access it other than directly, like writing

console.log(myConst);

Thx

window["myConst"] //would only work if myConst would have been defined using var

  • 2
    Why do you need to access a variable by its name? What are you trying to achieve? Because I think there should be a better way to solve the issue. – Reyno Mar 01 '23 at 12:21
  • 2
    You can't, it's a variable. Store your data into an [object](https://stackoverflow.com/questions/4244896/accessing-an-object-property-with-a-dynamically-computed-name) instead. – Teemu Mar 01 '23 at 12:21
  • 1
    This question comes up all the time. In some programming languages it makes sense. In JavaScript it means you're approaching a problem with a solution inappropriate for JavaScript. – Pointy Mar 01 '23 at 12:27
  • @Reyno: I developed an html element (a search box) where you can set configuration data for that element with a html property (like data-config="variableName"). So i have the name of that variable which has to be defined somewhere in your .js files.. It was a var before, but i wanted to chage it to const, hence window["variableName"] didn't work anymore – rantanplan55 Mar 01 '23 at 13:08

0 Answers0