1

Let say I got a string with the name of the variable I want to create.

If I want to create it with a global scope, I'd use window["myString"] = 100; or global["myString"] = 100; on Nodejs.

Is there a way to do the same but create the variable with local scope? (Ex: Inside a function)

EDIT: Note: The goal is to access the variable with its name directly. Ex: myString

I already know that I could easily create a object that would have the value as an attribute. Ex: obj.myString. But this is not what I'm looking for.

RainingChain
  • 7,397
  • 10
  • 36
  • 68
  • 1
    Why not just declare it a variable with `var` if you want it inside a local scope? eg: `var x = {}; x.myString = 100;` – Ben Fortune Jun 20 '14 at 15:14
  • 2
    Create an object, put properties on it, access the object's properties dynamically, profit! – Niet the Dark Absol Jun 20 '14 at 15:15
  • Here's another co-duplicate of that master duplicate question: [Get access to local variable or variable in closure by its name](http://stackoverflow.com/questions/2336508/javascript-get-access-to-local-variable-or-variable-in-closure-by-its-name) – apsillers Jun 20 '14 at 15:18

1 Answers1

0

The local scope is not exposed as the global object is.

However...

function someFunction() {
    var locals = {};

    locals['someLocalVar'] = 'local var';
}
plalx
  • 42,889
  • 6
  • 74
  • 90