-3

I was wondering if there was a function to create a variable, like new Object(), new Array(), etc. So, does something like new Variable("variable name", "value") exists? Thanks

EDIT: I know the var keyword... My goal was a function to create a variable which we could set the name with another variable... I saw the comment which was to make something like eval(var ${name};), that's what I would need, but how can I verify if it doesn't exist yet?

Demo
  • 31
  • 4
  • 8
    More importantly, why? – Taplar Dec 24 '18 at 21:06
  • To make my javascript knowledge grow – Demo Dec 24 '18 at 21:09
  • Maybe to define variables with names of other variables – Demo Dec 24 '18 at 21:11
  • I'm not aware of any built in method that allows you to pass in the variable name on the arguments. That doesn't make sense. Names are irrelevant to variable instantiations. You instantiate them, and then you put them in whatever variable, or *variables*, name you want. Consider your examples of Object and Array. You don't pass in the variable name there. – Taplar Dec 24 '18 at 21:13
  • 2
    @Demo There's always ``eval(`var ${name};`)``, but you really should never have dynamically named variables. Use a collection (e.g. an object with dynamic properties) instead. – Bergi Dec 24 '18 at 21:14
  • *Maybe to define variables with names of other variables* Please elaborate on that. – Taplar Dec 24 '18 at 21:17
  • How do you imagine it would be used once created in that manner? – Herohtar Dec 24 '18 at 21:21
  • Also, this is a duplicate of https://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript – Herohtar Dec 24 '18 at 21:27

3 Answers3

1

Yeah, something like that can be done for functions with Function constructor it is a bad practice in general I guess, and requires some weird use case...

console.log(new Function('a', 'b', 'return a + b'));
console.log(new Function('a', 'b', 'return a + b')(2,3));

Some nice reading about creating functions (got idea from there): https://javascript.christmas/2018/13

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Valery Baranov
  • 368
  • 3
  • 10
0

var name = value; should suffice. No need to create a function to set a variable.

https://www.w3schools.com/js/js_variables.asp

Cyrus
  • 613
  • 1
  • 6
  • 22
-1

For a global variable you could do:

var myVariableName = 'foo';

if(window[myVariableName] === undefined){
   window[myVariableName] = 'bar';
}


console.log('foo=', foo)// or console.log(window.foo)

Do similar on any other scoped object variable

charlietfl
  • 170,828
  • 13
  • 121
  • 150