0

I want to use a string as a variable name. But do not know how to do this. There are maybe many others way like map. But I want to know the similar way like this:

var ibrahim = 100

console.log(window['ibrahim'])

output: 100

Example code

In JavaScript, if we declare a variable with var then it will store in the global scope. For that, we can access that variable through the windows object.

This method only works for var.

I want to know if is there any similar way to do this with const and let?

mdibuhossain
  • 111
  • 2
  • 6
  • 1
    No, this is specific for `var` (and implicit globals). – trincot Nov 13 '22 at 19:56
  • Use an object or `Map` to present only the particular variables that you want accessible via a string. – Bergi Nov 13 '22 at 22:12
  • `var` will only store on `window` if it's used in the global scope. If it's used in another scope, the variable will be local to that scope. – Lennholm Nov 13 '22 at 22:21

1 Answers1

0

No, there is no other way. You need to declare window properties using var.

Steven Spungin
  • 27,002
  • 5
  • 88
  • 78