0

I have a variable with an object. If I declare the variable with var I can call it dynamically with a string from the windows object.

works!

var obj_1 = {
  say: "Hello World"
}

str = "obj_" + 1
console.log(window[str])

dont work

const obj_1 = {
  say: "Hello World"
}

str = "obj_" + 1
console.log(window[str])
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
  • 1
    Read the documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const#description It is clearly explained in the description on MDN. – epascarello Nov 11 '22 at 19:17
  • 2
    `const` and `let` are not in the global scope – LeoDog896 Nov 11 '22 at 19:17
  • 1
    Does this answer your question? [What is the difference between "let" and "var"?](https://stackoverflow.com/questions/762011/what-is-the-difference-between-let-and-var) – LeoDog896 Nov 11 '22 at 19:17
  • 1
    FYI: doing that is a bad pattern. Use an object or set. – epascarello Nov 11 '22 at 19:19
  • 1
    "Global constants do not become properties of the window object, unlike var variables." [const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) – Angel Dinev Nov 11 '22 at 19:20
  • Thanks at all commentors. now i understand! @epascarello Can you explain how it would look, please? – Maik Lowrey Nov 11 '22 at 19:33
  • 1
    no different than window. except you store the things in the set or object. `const data = { obj_ 1: 1, obj_ 2: 2 };` and access it like you did. `console.log(data[str]);` – epascarello Nov 11 '22 at 19:36
  • @epascarello That makes total sense! Thank you very much! – Maik Lowrey Nov 11 '22 at 19:38

0 Answers0